(function(){
	$.fn.computeTotal = function() {
		var cutOff = $(this).data("cutoff");
		var candidate = $(this).data("candidate");
		var tr = $(this).parents("tr");
		var computation = $.computeTotal({tr: tr, cutOff: cutOff});
		$(tr).find(".sumtotal").html(computation.total);
		$(tr).find(".cutoff").html(computation.lessCutOff);
		$(tr).find(".summary").html(computation.summary);
	}
})(jQuery)

jQuery(document).ready(function($){
	$.extend({
		computeTotal: function(options) {
			var total = 0;
			for (var i = 0; i < $(options.tr).find(".score_in").length; i++) {
				var val = parseInt($(options.tr).find(".score_in")[i].value);
				if(isNaN(val)) {
					val = 0
				}
				var max = parseInt($(options.tr).find(".score_in")[i].dataset.max);
				if(isNaN(max)) {
					max = 100
				}
				if(val > max) {
					$(options.tr).find(".score_in")[i].value = val = max;
				}
				total += val;
			}
			var lessCutOff = eval(total - options.cutOff);
			return {
				total: total,
				cutoff: options.cutOff,
				lessCutOff: lessCutOff,
				summary: function() {
					if(lessCutOff >= 0) {
						return '<span class="badge badge-success">Pass</span>';
					} else return '<span class="badge badge-danger">Failed</span>';
				}
			};
		}
	});
	$(".score_in").each(function(i, obj){
		$(obj).computeTotal();
	})
}).on("keyup", ".score_in", function(){
	$(this).computeTotal();
})