
var FieldDependency = new Class({
	/*
	 * A simple field dependency tool. Field A is dependent on field B's 
	 * values X if it is visible whenever field B has a value in X 
	 * and hidden otherwise. Field A is the dependent field and B the 
	 * governing field.
	 */
	initialize : function(dependent_field, governing_field, show_values, governing_field_selector) {
		/*
		 * The element $(dependent_field) will be hidden unless 
		 * $(governing_field).value is in show_values.
		 * governing_field_selector is a function from the governing 
		 * field id to the field element (the id may, for example, need 
		 * to point to a container element for some reason).
		 */
		this.dependent_field = dependent_field;
		this.governing_field = governing_field;
		this.governing_field_selector = governing_field_selector;
		this.show_values = show_values;
		
		// Hook the update routine onto the governing field's change event
		this.getGoverningField().addEvent('change', this.updateVisibility.bind(this));
		
		// Set the visibility to start with
		this.updateVisibility();
	},
	
	getDependentField : function() {
		return $(this.dependent_field);
	},
	
	getGoverningField : function() {
		if (undefined==this.governing_field_selector) {
			return $(this.governing_field);
		} else {
			return this.governing_field_selector(this.governing_field);
		}
	},
	
	getGoverningValue : function() {
		return this.getGoverningField().value;
	},
	
	updateVisibility : function() {
		/*
		 * Sets the dependent field to be visible or hidden, as 
		 * dictated by the governing value.
		 */
		var value = this.getGoverningValue();
		var found = false;
		for (var i=0; i<this.show_values.length; i++) {
			if (this.show_values[i] == value) {
				found = true;
				break;
			}
		}
		
		if (found) {
			// This value is one that allows the dependent field to display
			this.showField();
		} else {
			this.hideField();
		}
	},
	
	showField : function() {
		var field = $(this.dependent_field);
		field.setStyle('display', '');
	},
	
	hideField : function() {
		var field = $(this.dependent_field);
		field.setStyle('display', 'none');
	}
});
