﻿

//
// This is object that holds a reference to all of our condition functions and so on.
//
Condition = new Object();
Condition.conditions = new Array();

Condition.initialise = function() {

    if (this.conditions.length == 0) {
        // if there ARE NO conditions, don't do anything
        return;
    }

    // attach a handler to all of the controls that can affect whether questions are shown/hidden and
    // call check() whenever they change
    $(".question")
            .find("input[type=checkbox], input[type=radio], select, div.rate-stars").click(function() { Condition.check(); }).end()
            .find("input[type=text], textarea").blur(function() { Condition.check(); }).end()
    // any more?
        ;

    this.check(true);
}

//
// Goes through all of the conditions and checks for any questions that
// need to be shown/hidden
//
Condition.check = function(immediate) {
    for (var i = 0; i < this.conditions.length; i++) {
        var cond = this.conditions[i];
        var qp = $("div[qpid=" + cond.qpid + "]");

        if (cond.check()) {
            qp.show();
        } else {
            if (immediate) {
                qp.hide();
            } else {
                qp.hide();
            }

            // also, uncheck any checkboxes, remove any text, etc...
            $("input[type=checkbox], input[type=radio]", qp).attr("checked", "");
            $("input[type=text], input[type=hidden]", qp).val("");
        }
    }
}

//
// Constructs a new QuestionPartCondition object which contains the condition logic for
// a given question part.
//
function QuestionPartCondition(qpid, fn) {
    this.qpid = qpid;
    this.fn = fn;
}

//
// Checks whether the question part that we represent should be shown/hidden. Returns
// true if we should be visible, false if we should be hidden.
//
QuestionPartCondition.prototype.check = function() {
    return this.fn();
}
