function compute_moyenne() {
    var notes = $(".tf_field_note input").map(
        function () { return parseFloat($(this).val()); }
    ).get();
    // les coefs sont donnes (ECTS en BUT)
    let coefs = $("form.tf_ext_edit_ue_validations").data("ue_coefs");
    // ou saisis (formations classiques)
    if (coefs == 'undefined') {
        coefs = $(".tf_field_coef input").map(
            function () { return parseFloat($(this).val()); }
        ).get();
    }
    var N = notes.length;
    var dp = 0.;
    var sum_coefs = 0.;
    for (var i = 0; i < N; i++) {
        if (!(isNaN(notes[i]) || isNaN(coefs[i]))) {
            dp += notes[i] * coefs[i];
            sum_coefs += coefs[i];
        }
    }
    let moy = dp / sum_coefs;
    if (isNaN(moy)) {
        moy = "-";
    }
    if (typeof moy == "number") {
        moy = moy.toFixed(2);
    }
    return moy;
}

// Callback select menu (UE code)
function enable_disable_fields_cb() {
    enable_disable_fields(this);
}
function enable_disable_fields(select_elt) {
    // input fields controled by this menu
    var input_fields = $(select_elt).parent().parent().find('input:not(.ext_coef_disabled)');
    var disabled = false;
    if ($(select_elt).val() === "None") {
        disabled = true;
    }
    input_fields.each(function () {
        if (disabled) {
            let cur_value = $(this).val();
            $(this).data('saved-value', cur_value);
            $(this).val("");
        } else {
            let saved_value = $(this).data('saved-value');
            if (typeof saved_value == 'undefined') {
                saved_value = '';
            }
            if (saved_value) {
                $(this).val(saved_value);
            }
        }
    });
    input_fields.prop('disabled', disabled);
}
function setup_text_fields() {
    $(".ueext_valid_select").each(
        function () {
            enable_disable_fields(this);
        }
    );
}

$().ready(function () {
    $(".tf_ext_edit_ue_validations").change(function () {
        $(".ext_sem_moy_val")[0].innerHTML = compute_moyenne();
    });
    $("form.tf_ext_edit_ue_validations input").blur(function () {
        $(".ext_sem_moy_val")[0].innerHTML = compute_moyenne();
    });
    $(".ueext_valid_select").change(enable_disable_fields_cb);

    setup_text_fields();
});