$(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 = '<div class="alert alert-success" role="alert"><strong>Great!</strong> Your solution is correct.<br/></div>';
				$("#continue").prop( "disabled", false);
			} else if (msg.data.grade == "FAIL") {
				html = '<div class="alert alert-danger" role="alert"><strong>Sorry!</strong> That is not correct.<br/></div>';
			} else {
				// assume test
				//html = msg;
				// a possible message that is generated yb the server to give tips?
			}
		}

		if ( output != false ) {
			$("#output-wrapper").show(500);
			$("#output").html(output);
		}

		$("#response").hide().html(html).show(500);


		$("#submit-test").prop( "disabled", false);
		$("#submit-grade").prop( "disabled", false);

	}


	solution = {}
	solution.gather = function () {
		console.log("Gather solution!");

		sol = Array();

		$("#exercise-choices input:checked").each(function () {
			console.log($(this).attr("value"));
			sol.push($(this).attr("value"));

		});

		return sol;
	}



	job = {}
	job.submit = function (action) {

		sol = solution.gather()

		submission = {"solution": sol, "slide": window.data.slide, "action": "quiz"};
		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);
			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-grade").click(function(event) {
		$("#submit-grade").prop( "disabled", true);
		job.submit("grade");
	});


	/**
	 * Extend clickable area for checkboxes and radio buttons to the parent.
	 * Optional: Add background coloring
	 */
	$("#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-userchoice");


	});


});
