$(function()
	{
		// Activate clipboard support for class "mbd-clipboard"; be sure to run it on DOM-ready (else clipboard.js won't be happy)
		new ClipboardJS('.mbd-clipboard');

		// Localize dates to browser's settings
		$('.mbd-localize-date').each(function()
			{
				$(this).text(new Date($(this).text().trim()).toLocaleString());
		});

		$(document)
			// Show 'wait' cursor on load() (or other ajax functions)
			.ajaxStart(function(){$(document.body).css({'cursor': 'wait'});})
			.ajaxStop(function(){$(document.body).css({'cursor': 'default'});})
			// Hide popup on ESC key
			.keyup(function(e) { if (e.keyCode == 27) { $('#mbd-api-popup').addClass('mbd-hidden'); }});

			// Show "date-time limit" on demand (getting along with potential javascript absence)
			$('.mbd-events-limit-before').prop({'disabled': true, 'hidden': true});
			$('.mbd-events-limit-before-check').prop({'disabled': false, 'hidden': false});
			$('.mbd-events-limit-before-check').click(function()
			                                          {
			                                          	if($(this).prop('checked') == true)
			                                          	{
			                                          		$('.mbd-events-limit-before').prop({'disabled': false, 'hidden': false});
			                                          	}
			                                          	else
			                                          	{
			                                          		$('.mbd-events-limit-before').prop({'disabled': true, 'hidden': true});
			                                          	}
			                                          });

		// Treat "omnipresent search form" specially
		const $form = $('body>header>nav>ul>li>form[action$="/search/"]');
		const $inputText = $form.find('input[type="text"][name="pattern"]').first();
		const $inputSubmit = $form.find('input[type="submit"]').first();
		const tooltipText = $inputSubmit.attr('title') || '';
		const tooltipHtml = tooltipText.replace(/\n/g, '<br>');
		$inputText.attr('placeholder', 'Search for packages');
		$inputText.addClass('show-placeholder');
		$form.on('mouseenter', function(e)
		                       {
		                       	if (tooltipHtml) {$('div.mbd-tooltip').html(tooltipHtml).show().css({top: e.clientY+28, left: e.clientX});}
		                       }
		).on('mousemove', function(e)
		                  {
		                  	left = e.clientX;
		                  	if (window.matchMedia('(max-width: 640px)').matches)
		                  	{
		                  			left = 0;
		                  	}
		                  	else if (window.matchMedia('(max-width: 75rem)').matches)
		                  	{
		                  			left = $(window).width()/2;
		                  	}
		                  	$('div.mbd-tooltip').css({top: e.clientY+30, left: left});
		                  }
		).on('mouseleave', function()
		                   {
		                   	$('div.mbd-tooltip').hide();
		                   });

		// search progress indicator
		$form.append('<progress id="mbd-search-progress"></progress>')
		$form.on('submit', function()
		                   {
		                   	$inputText.blur();
		                   	$form.find('span').first().css('filter', 'opacity(50%)');
		                   	$('#mbd-search-progress').css('display', 'block');
		                   	$('div.mbd-tooltip').remove();
		                   });

		// Back button
		if (history.length > 1)
		{
			$('.mbd-back-button')
				.css('display', 'inline-block')
				.on('click', function (e) {e.preventDefault(); history.back();});
		}
});

// alert on next event (test code, for reference only).
function mbd_event()
{
	$.ajax({url: "/static/events.attach", dataType: "json", complete: function(xhr, status)
		{
			console.log("EVENT", xhr);
			alert(JSON.stringify(xhr.responseJSON, null, 2));
	}});
}

function mbd_api_call(form, command)
{
	const api_uri = "/mini_buildd/api/";
	const args = $(form).serializeArray()
	const output = args.filter(kv => kv.name == "output")[0].value
	if (output != "html") { return true; }  // Skip, allow non-js 'action=' to be performed

	// Discard empty values mainly for convenience (shorter uris, nicer display) -- args w/ empty values are treated as 'not given' by API anyway.
	const args_cleaned = $(form).serializeArray().filter(kv => kv.name != "output" && kv.value != "");

	$("#mbd-api-popup-content").html("<div style='text-align: center; font-size: x-large;'>Running API call <strong>" + command + "</strong>...</div><progress style='width: 100%'></progress>");
	$("#mbd-api-popup").removeClass("mbd-hidden")
	$("#mbd-api-popup-content").load(api_uri + command + "/?" + jQuery.param(args_cleaned) + "&confirm=" + command + "&output=html-snippet",
																	 function (response, status, xhr)
																	 {
																		 if (status == "error")
																		 {
																			 $("#mbd-api-popup-content").html(response);
																		 }
																		 else if (["start", "stop"].includes(command))
																		 {
																			 location.reload();
																		 }
																	 });
	return false;  // Avoid non-js 'action=' to be performed
}
