$(document).ready(function () {
	$(document).on('click', "#btn-frame-download", function () {
		//first add the logos
		addLogos();
		var element = document.getElementById("graph-collection"); // global variable
		if (element == null) {
			element = document.getElementById("prob-graph"); // global variable
			if (element == null) {
				element = document.getElementById("was-graph"); // global variable
			}
		}
		getCanvas(element);
		removeLogos();
	});
});

function getCanvas(element) {
	html2canvas(element, {
		scrollX: 0,
		scrollY: 0,
		allowTaint: true,
		useCORS: true,
		async: true,
		windowWidth: element.offsetWidth + 30,
		windowHeight: element.offsetHeight,
		logging: true,
		imageTimeout: 0,
		ignoreElements: function( element ) {
			if( element.classList.contains( 'leaflet-control-zoom' )) {
				return true;
			}
		}
	}).then(function (canvas) {
		saveAs(canvas.toDataURL(), 'image.png');
	});
}

function saveAs(uri, filename) {
	var link = document.createElement('a');
	if (typeof link.download === 'string') {
		link.href = uri;
		link.download = filename;

		//Firefox requires the link to be in the body
		document.body.appendChild(link);

		//simulate click
		link.click();

		//remove the link when done
		document.body.removeChild(link);
	} else {
		window.open(uri);
	}
}

//Add logos top map for screen shot
function addLogos() {
	const logos = document.getElementById('logos');
	if (logos){
		logos.style.display = 'inline';
	} else {
		var img = new Image();
		img.src = './assets/images/logoline.png';
		img.style.position = 'absolute';
		img.style.maxWidth = '35%';
		img.style.width = 'auto';
		img.style.maxHeight = '10%';
		img.style.height = 'auto';
		img.style.top = '6';
		img.style.marginTop = '7px';
		img.style.right = '1%';
		img.style.zIndex = '999';
		img.setAttribute('id','logos');

		// Get the element to overlay the image on
		var div = document.querySelector('.leaflet-control-container');

		// Append the image to the element
		div.appendChild(img);
	};
}

function removeLogos() {
	var logos = document.getElementById('logos');
	logos.remove();
};
