var formpartdisabler = {

    rules: [],

    addRule: function(source, subject, disable) {
        this.rules[this.rules.length] = { source: source, subject: subject, disable: disable };
        $(source).click(function() { formpartdisabler.updateSubject(subject) });
        $(source).change(function() { formpartdisabler.updateSubject(subject) });
    },

    update: function() {
        for (var i = 0; i < this.rules.length; i++) {
            this.updateSubject(this.rules[i].subject);
        }
    },

    updateSubject: function(subject) {
        var ruleExists = false;
        for (var i = 0; i < this.rules.length; i++) {
            if (this.rules[i].subject == subject) {
                ruleExists = true;
                if ($(this.rules[i].source).is(':checked') || $(this.rules[i].source).is(':selected')) {
                    if (this.rules[i].disable)
                        this.disableSubject(subject);
                    else
                        this.enableSubject(subject);
                    $('input', $(subject)).each(function() {
                        formpartdisabler.updateSubject('#' + this.id);
                    });
                    return;
                }
            }
        }
        if(ruleExists)
            this.disableSubject(subject);
    },

    enableSubject: function(subject) {
        if ($(subject).is(':input')) {
            $(subject).removeAttr("disabled");
        } else {
            $('input', $(subject)).removeAttr("disabled");
        }
    },

    disableSubject: function(subject) {
        if ($(subject).is(':input')) {
            $(subject).attr("disabled", true);
        } else {
            $('input', $(subject)).attr("disabled", true);
        }
    }

}