jQuery(document).ready(function($){
  $("#category, #ext_exam, #course, #term, #class").change(function(){
    if($("#class").val() !== "" && $("#category").val() !== "" && $("#ext_exam").val() !== "" && $("#course").val() !== "") {
      $("#"+ $(this).data("form")).submit();
    }
  })
  $("#class, #category").change(function(){
  	$("#course").val("");
  	if($("#class").val() !== "" && $("#category").val() !== "") {
  		var class_id = $("#class").val();
  		var category_id = $("#category").val();
		$.ajax({
		    type: 'POST',
		    url: 'contents/plugins/external_examination/ajax.php',
		    data: {action: 'get_class_courses', class_id: class_id, category_id: category_id},
		    success: function(data) {
		    	data = JSON.parse(data);
		    	if(data.error == 0) {
		    		$("#course").empty();
		    		$("#course").append('<option value="">Select...</option>');
		    		var html = "";
		    		for(var course_id in data.courses) {
		    			html += '<option value="'+course_id+'">'+data.courses[course_id]+'</option>';
		    		}
		    		$("#course").append(html).trigger("chosen:updated");
		    	} else if(data.error == 1) {
		    		$("#course").empty();
		    		var html = "<option value=''>Select...</option>";
		    		$("#course").append(html);
		    	}						
		    },
		    error: function(xhr, status, error) {
		    	$("#course").empty();
		    	$("#course").append('<option value="">Select...</option>');
		    }
		});
  	}
  });

  $(".score").keyup(function(){
  	var id = $(this).attr("id");
  	var element = document.getElementById(id);
  	if($(this).val() > 100) {
  		$(this).val(100);
  		calculate_grade(element);
  	}
  	if($(this).val() < 0) {
  		$(this).val(0);
  		calculate_grade(element);
  	}
  })

});