$(document).ready(function () {
	response = {};
	response.show = function (type, msg, output) {
		console.log("show issued" + type + msg);
		html = "";
		if (type == "test") {
		} else {
			if (msg.data.grade == "PASS") {
				html = '
Great! Your solution is correct.
';
				$("#continue").prop( "disabled", false);
			} else if (msg.data.grade == "FAIL") {
				html = 'Sorry! That is not correct.
';
			} else {
				// assume test
				//html = msg;
				// a possible message that is generated yb the server to give tips?
			}
		}
		
		console.log(output)
		if ( output == "" ) {
			output = " "
		}
		if ( output != false) {
			console.log("output is not false")
			$("#output-wrapper").show(500);
			$("#output").html(output);
		} 
		$("#response").hide().html(html).show(500);
		$("#submit-test").prop( "disabled", false);
		$("#submit-grade").prop( "disabled", false);
	}
	job = {}
	job.submit = function (action) {
		console.log("Test submission issued..");
		console.log( $("#solution").val() );
		submission = {"solution": $("#solution").val(), "action": "quiz", "slide": window.data.slide};
		submission_json = JSON.stringify(submission);
		console.log(submission_json)
		$.ajax({
			method: "POST",
			url: "/api/rest/job/new/",
			contentType: 'application/json',
			data: submission_json
		})
		.done(function( msg ) {
			console.log("Job submitted: " + msg );
			console.log(msg);
			job_id = msg['id'];
			setTimeout(function(){ job.status(action, job_id); }, 1000);
		});	
	};
	job.status = function (type, job_id) {
	
		console.log(type)
		e = {"blub": "hm"};
		json_data = JSON.stringify(e);
		$.ajax({
			method: "GET",
			url: "/api/rest/job/" + job_id + "/",
			contentType: 'application/json',
		})
		.done(function( msg ) {
			console.log("Status received: " + msg );
			console.log(msg);
			if ( msg.status == 'SUCCESS' ) {
				response.show(type, msg, msg.data.output);
			} else {
				response.show(type, "processing...", false);
				setTimeout(function(){ job.status(type, job_id); }, 3000);
			}
		});
	};
	$("#submit-test").click(function(event) {
		$("#submit-test").prop( "disabled", true);
		job.submit("test"); 
	});
	$("#submit-grade").click(function(event) { 
		$("#submit-grade").prop( "disabled", true);
		job.submit("grade");
	});
	$("#exercise-choices a.list-group-item").click(function(event) {
		event.preventDefault()
		//$("#submit-test").prop( "disabled", true);
		//job.submit("test"); 
		
		target = event.target
	
		if ( $(target).is('input') ) {
			target = $(event.target).parent()[0]
		} else {
			// also check/uncheck when clicking surounding
		}
		//if ( $(target).children("input").attr('type') == 'radio' ) {
		//	$(target).parent().children(".list-group-item-success").removeClass("list-group-item-success");
		//}
		console.log(target)
		$(target).children("input").each(function () { this.checked = !this.checked; console.log(this) });
		//$(target).toggleClass("list-group-item-success");
	});
});