
/* JS for the Diet & Fitness self-assessments. Some of this code runs immediately when the script is 
referenced (i.e. not in response to user action) so it's important to import this script at the end of
the page to ensure that the HTML objects it references are created by the time the script runs.
*/ 

var sectionNames = [ ];

// Here I cache a list of the radio buttons in the quiz and also compute how many unique 
// sections (questions) exist.
var buttons = document.getElementById("quiz").getElementsByTagName("input");
for (var i = 0;  i < buttons.length; i++) {
    var pushit = true;
    for(var j=0; j<sectionNames.length; j++) {
        if(sectionNames[j] == buttons[i].name) {
            pushit = false;
            break;
        }
    }
      if (pushit) {
        sectionNames.push(buttons[i].name);
    }
}
        
function calculateTotal() {
    // This function is inelegant in that it loops through all of the radio buttons every time
    // a single button is clicked. There's probably nicer ways to do this, but this approach has 
    // some desirable features --
    // - Works in all browsers I tested 
    // - Gracefully handles a page refresh where this script gets reinitialized but the state of the 
    //   radio buttons does not
    // - Should work even under browsers that allow one to explicitly deselect a selected radio      
    //   button (although none of my test browsers permit this).
    var total = 0;
    var completedSections = 0;
    
    for (var i = 0;  i < buttons.length; i++) {
        if (buttons[i].checked) {
            total += parseInt(buttons[i].value);
            // Since these are radio buttons and only one can be selected per section, each selected
            // button implies a different section.
            completedSections += 1;
        }
    }
    document.getElementById("total").innerHTML = total.toString();
    
    // I display the totals and scoring if & only if there's an answer in every section.
    if (completedSections == sectionNames.length) {
        document.getElementById("incomplete").style.display = "none";
        document.getElementById("complete").style.display = "block";
    }
    else {
        document.getElementById("incomplete").style.display = "block";
        document.getElementById("complete").style.display = "none";
    }
}

calculateTotal();


