$(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 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() {
	//This function removes the added logos after screenshot is taken
	var logos = document.getElementById('logos');
	logos.remove();
};

function makeChanges() {
	//colorbar needs pushed down for picture
	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.remove();
}

function removeChanges() {
	//put colorbar back in place
	const colorbar = document.querySelector('.leaflet-control-colorbar');
	colorbar.style.paddingTop = '0px';
	//remove added logos 
	removeLogos();
}


