$(document).ready(function () {
	$(document).on('click', "#btn-frame-download", function () {
		// First add the logos
		// Adjust colorbar, as it is appearing covered by the info bar
		makeChanges();
		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);
		// The changes need to be remove to ensure the map appears normal
		removeChanges();
	});
});

function getCanvas(element) {
	html2canvas(element, {
		scrollX: 0,
		scrollY: 0,
		allowTaint: true,
		useCORS: true,
		async: true,
		windowWidth: element.offsetWidth + 90,
		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 AT THE TOP OF THE MAP FOR THE SCREENSHOT
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);
	};
}

// REMOVE LOGOS AFTER SCREENSHOT IS TAKEN
function removeLogos() {
	var logos = document.getElementById('logos');
	logos.remove();
};

// PUSH DOWN COLORBAR FOR SCREENSHOT
function makeChanges() {
	// Push down
	const colorbar = document.querySelector('.leaflet-control-colorbar');
	colorbar.style.paddingTop = '60px';
	// Add the logos for the screenshot
	addLogos();
	// Remove the attribution in the bottom right corner
	const attribution = document.querySelector('.leaflet-control-attribution');
	attribution.style.display = "none";
}

// RETURN COLORBAR TO INITIAL POSITION AFTER SCREENSHOT
function removeChanges() {
	// Put colorbar back in place
	const colorbar = document.querySelector('.leaflet-control-colorbar');
	colorbar.style.paddingTop = '0px';
	// Remove added logos 
	removeLogos();
}


