var Questioning = {
	qualifierInputMatcher: /^choice_qualifier_(\d+)_(\d+)$/,
	choiceInputMatcher: /^choice_(\d+)_(\d+)$/,

	fixQualifierVisibility: function(event, select) {
		var questionId = /^select_(\d+)$/.exec(select.id)[1];
		var choiceId = select.options[select.selectedIndex].value;
		$A(document.getElementsByTagName("input")).each(function(item) {
			var match = this.qualifierInputMatcher.exec(item.id);
			if (match) {
				var qualifierQuestionId = match[1];
				var qualifierChoiceId = match[2];

				if (qualifierQuestionId == questionId) {
					item.style.display = (qualifierChoiceId == choiceId ? "inline" : "none");
				}
			}
		}.bind(this));
	},

	addQualifierInputEvents: function() {
		$A(document.getElementsByTagName("input")).each(function(item) {
			var match = this.qualifierInputMatcher.exec(item.id);
			if (match) {
				Event.observe(item, 'keyup', this.onQualifierChange.bindAsEventListener(this, item, $('choice_' + match[1] + '_' + match[2]), match[1]));
			}

			match = this.choiceInputMatcher.exec(item.id);
			if (match) {
				Event.observe(item, 'change', this.clearRadioQualifiers.bindAsEventListener(this, item, match[1], match[2]));
			}
		}.bind(this));
	},

	onQualifierChange: function(event, item, checkBox, questionId) {
		if (checkBox.type == 'radio') {
			$A(document.getElementsByTagName("input")).each(function(element) {
				var match = this.qualifierInputMatcher.exec(element.id);
				if (match && match[1] == questionId && element != item) {
					element.value = ''
				}
			}.bind(this));
		};

		checkBox.checked = item.value != '';
	},

	clearRadioQualifiers: function(event, item, questionId, choiceId) {
		if (item.type == 'radio') {
			$A(document.getElementsByTagName("input")).each(function(element) {
				var match = this.qualifierInputMatcher.exec(element.id);
				if (match && match[1] == questionId) {
					element.value = ''
				}
			}.bind(this));

		} else if (!item.checked){
			var qualifier = $('choice_qualifier_' + questionId + '_' + choiceId);
			if (qualifier) {
				qualifier.value = '';
			}
		}
	}
}
