﻿
//
// Creates a new ValidationQuestion object which we add to the Validation.questions array
// to represent the validation options for the given question/question part.
//
function ValidationQuestion(qid, qpid, fn) {
    this.questionID = qid;
    this.questionPartID = qpid;
    this.fn = fn;
}

// This object is used to do all of the client-side validation for the page.
Validation = new Object();
Validation.firstTime = true;

//
// The javascript on the page will populate this with one function per
// question-part to do the actual validation. It'll be up to us to call these
// and fill in the error message at the appropriate place.
//
Validation.questions = new Array();

//
// This is call when you click "Submit" to actually validate the options
// you've selected.
//
Validation.validate = function() {
    var errors = false;
    for (var i = 0; i < this.questions.length; i++) {
        var qn = this.questions[i];

        var qp = $(".question[qid=" + qn.questionID + "] .question-part[qpid=" + qn.questionPartID + "]");

        if (qp.css("display") == "none") {
            // if this question part isn't visible (e.g. the conditions haven't been met, etc) then
            // just skip it, you don't have to answer it anyway
            continue;
        }

        // call the validation function to get the message
        var msgNode = $(".validation-error", qp);
        var msg = qn.fn();
        if (msg != null) {
            // if there's a message, it means we failed validation and
            // have to a) display the message to the user, and cancel
            // the "Submit".
            errors = true;

            msgNode.text(msg).show("fast");
        } else {
            msgNode.hide("fast");
        }
    }

    // If this is the first time we got an error, we'll attach event handlers to all of the
    // controls so that we can dynamically update the error messages as you change/fix things...
    if (errors && this.firstTime) {
        this.firstTime = false;

        $(".question")
            .find("input[type=checkbox], input[type=radio], select, div.rate-stars").click(function() { Validation.validate(); }).end()
            .find("input[type=text], textarea").blur(function() { Validation.validate(); }).end()
        // any more?
        ;
    }

    return !errors;
}
