(function($) {

	var
		hamburgerTl = gsap.timeline({ paused: true }),
		primaryMenuTl = gsap.timeline({ paused: true }),
		duration = .5,
		line_1 = '#menu-handle .hamburger span:nth-child(1)',
		line_2 = '#menu-handle .hamburger span:nth-child(2)',
		line_3 = '#menu-handle .hamburger span:nth-child(3)';

	hamburgerTl
		.to([line_1, line_3], {
			top: '50%',
			ease: 'power3.in',
			duration: duration
		})
		.to(line_2, {
			autoAlpha: 0,
			ease: 'power3.in',
			duration: duration
		}, 0)
		.add('cross')
		.to([line_1, line_3], {
			width: '100%',
			height: 4,
			left: 0,
			marginTop: -2,
			marginLeft: 0,
			duration: duration,
			ease: 'back.out'
		})
		.to(line_1, {
			rotation: 45,
			duration: duration,
			ease: 'back.out'
		}, 'cross')
		.to(line_3, {
			rotation: -45,
			duration: duration,
			ease: 'back.out'
		}, 'cross');

	function handleMenu() {

		event.preventDefault();

		$(this).toggleClass('open');

		if($(this).hasClass('open')) {
			hamburgerTl.play();
			gsap.to('#primary-menu-wrapper', {
				height: 'auto',
				ease: 'back.out',
				duration: duration * 1.6
			});
		} else {
			hamburgerTl.reverse();
			gsap.to('#primary-menu-wrapper', {
				height: 0,
				ease: 'power3.inOut',
				duration: duration * 1.6
			});
		};

	};

	function toggleSubmenu(e) {

		e.stopPropagation();
		e.preventDefault();

		var
			target = $(this).parent().next('ul.sub-menu'),
			handler = $(this).find('.submenu-handler'),
			showVars = { height: 'auto', autoAlpha: 1, ease: 'back.out', duration: duration * 1.6 },
			hideVars = { height: 0, autoAlpha: 0, ease: 'power3.inOut', duration: duration * 1.6 },
			upVars = { rotation: 180, ease: 'back.out', duration: duration * 1.6 },
			downVars = { rotation: 0, ease: 'power3.inOut', duration: duration * 1.6 };

		target.toggleClass('open');

		if(target.hasClass('open')) {
			gsap.to(target[0], showVars);
			gsap.to(handler[0], upVars);
		} else {
			gsap.to(target[0], hideVars);
			gsap.to(handler[0], downVars);
		};

	};

	function prepareSubmenu() {

		var downButton = $('<button class="show-submenu"><i class="fas fa-fw fa-angle-down submenu-handler"></i></button>');
		$(this).find('> a').append(downButton);

		downButton.click(toggleSubmenu);

	};

	$('#menu-handle').click(handleMenu);
	$('.menu-item-has-children').each(prepareSubmenu);

	function setScroll() {
		if($(this).scrollTop() > 200) {
			$('body').addClass('scrolled');
		} else {
			$('body').removeClass('scrolled');
		};
	}

	$(window).load(setScroll);

	$(window).on('scroll', setScroll);

})(jQuery);
