jQuery(document).ready(function($){
	$(document).on("click", ".download-template-btn", function(e){
		e.preventDefault();
		if($("#offline-class-category").val() === "") {
			$.notify("Please Select Class");
			return;
		}
		var class_category = $("#offline-class-category").val();
		if($("#offline-ext-exam").val() === "") {
			$.notify("Please Select Examination");
			return;
		}
		var ext_exam = $("#offline-ext-exam").val();
		if($("#offline-term").val() === "") {
			$.notify("Please Select Term");
			return;
		}
		var term = $("#offline-term").val();
		var element = $("#download-template-btn");
		$(element).removeClass("download-template-btn");
		var text = $(element).html();
		var html = "<img src=\"contents/plugins/excel_result_compilation/images/we-are-working.png\"><p>Please Relax and take a chill pill as we work on your files. Your download will begin in about 2 minutes time or more depending on class population. <br />Do not close this window.</p><div class=\"loading\"><span><i></i><i></i></span></div>";
		$(element).html(html).attr("disabled", true);
		$.ajax({
			type: "post",
			url: "contents/plugins/excel_result_compilation/ajax.php",
			data: {action: "generate_mock_result_template_zip", class_category: class_category, term: term, ext_exam: ext_exam}
		}).done(function(data){
			try {
				data = JSON.parse(data);
				var url = data.file+"?version="+data.time
				var html = "<img src=\"contents/plugins/excel_result_compilation/images/done.png\"><p>We are done and I assure you that it was worth the wait. If your download did not start automatically, <a href=\""+url+"\" class=\"red\" download>Click Here to download it</a><br/>Or <a href=\"javaScript:void(0);\" class=\"green download-template-btn\" download>Click Here to download for New Selection</a></p>";
				$(element).html(html).attr("disabled", false);
				navigate(url, false, true);
			}
			catch(err) {
				console.log(err);
				console.log(data);
				$(element).html(text).attr("disabled", false);
				$(element).addClass("download-template-btn");
			}
			finally {}
		}).fail(function(err){
			$(element).html(text).attr("disabled", false);
			$(element).addClass("download-template-btn");
		})
	})
})