jQuery(document).ready(function($) {
	"use strict";

	//// Tabs
	$('#hootabt-tabs .hootabt-tab, .hootabt-shortcut').on('click',function(e){
		var isactive = $(this).hasClass('hootabt-active'),
			moduleid = $(this).data('inpage'),
			widen = $(this).data('widen'),
			$module = $('#hootabt-'+moduleid);
		if ( moduleid === undefined || ! $module.length )
			return;
		e.preventDefault();
		if ( isactive )
			return;

		var $tabs = $('#hootabt-tabs .hootabt-tab'),
			$modules = $('.hootabt-module'),
			isShortCut = $(this).hasClass('hootabt-shortcut');

		$tabs.removeClass('hootabt-active');
		if ( isShortCut ) $tabs.filter('[data-inpage="'+moduleid+'"]').addClass('hootabt-active');
		else $(this).addClass('hootabt-active');
		$modules.removeClass('hootabt-active');
		$module.addClass('hootabt-active');

		if ( widen )
			setTimeout(function() { $('#hootabt-wrap').addClass('hootabt-widen'); }, 100);
		else
			$('#hootabt-wrap').removeClass('hootabt-widen');

		// Update the URL with the new tab parameter
		var newUrl = new URL(window.location.href);
		newUrl.searchParams.set('tab', moduleid);
		history.replaceState(null, null, newUrl.toString());
		var $refererInput = $('.hootabt-module input[name="_wp_http_referer"]');
		if ($refererInput.length) {
			$refererInput.each(function() {
				var refererUrl = new URL($(this).val(), window.location.origin);
				refererUrl.searchParams.set('tab', moduleid);
				$(this).val(refererUrl.pathname + refererUrl.search);
			});
		}

		// Scroll to content
		if ( window.scrollY > 50 ) {
			$("html:not(:animated),body:not(:animated)").animate({ scrollTop: 0}, 200 );
		}
	});

	//// Goto Top
	var $hootabt = $('.hootabt-top');
	var lastScrollY = 0;
	var ticking = false;
	var isVisible = false;
	function onScroll() {
		lastScrollY = window.scrollY || window.pageYOffset;
		requestTick();
	}
	function requestTick() {
		if (!ticking) {
		requestAnimationFrame(update);
		ticking = true;
		}
	}
	function update() {
		if (lastScrollY >= 500) {
		if (!isVisible) {
			$hootabt.stop(true, true).fadeIn(150);
			isVisible = true;
		}
		} else {
		if (isVisible) {
			$hootabt.stop(true, true).fadeOut(150);
			isVisible = false;
		}
		}
		ticking = false;
	}
	$hootabt.hide();
	$(window).on('scroll', onScroll);
	$hootabt.on('click',function(e){
		var $target = $( $(this).attr('href') );
		if ( $target.length ) {
			e.preventDefault();
			var destin = $target.offset().top - 46; // 32px/46px admin bar for desktop/tablet
			$("html:not(:animated),body:not(:animated)").animate({ scrollTop: destin}, 500 );
		}
	});

});