/*
 * Author: Scott Steil <scott.steil@imperium.ca>
 * 
 * Update the fields of any form with a set of data. This is especially useful
 * for form validation that is preformed on the server side. In these cases, we
 * want the page to reload with the form data re-filled in. Since we can access 
 * the post data, we can use it to re-populate the form with the submitted data.  
 * This function will work for any type of input.
 */

var FormController = new Class({
	Implements: [Options],
	
	options: {
	},
	
	initialize: function(form, options){
		if(!$chk(form)) {
			return false;
		}
		this.setOptions(options);
		this.form = $(form);
		this.inputs = this.form.getElements('input, textarea, select');
	},
	
	/**
	 * This method takes a set of field values in a hash object and set the
	 * appropriate inputs. The field names should be the array's keys to the 
	 * associated values.
	 * returns 
	 */
	setValues: function(values) {
		var count = 0;
		var hash = new Hash(values);
		this.inputs.each(function(item) {
			var name = item.get('name');
			if(hash.has(name)) {
				this.setValueForField(item, hash.get(name));
				count++;
			}
		}.bind(this));
		return count == values.length;
	},
	/**
	 * Set the input with the specified name to store the specified value.
	 */
	setValue: function(name, value) {
		var success = false;
		this.inputs.each(function(item) {
			if(item.get('name') == name) {
				success = this.setValueForField(item, value);
			}
		}.bind(this));
		return success;
	},
	
	/*
	 * This function will check the type of input that a value is being assigned
	 * to and will ensure that the appropriate code is executed to set the value
	 */
	setValueForField: function(id, value) {
		var item = $(id);
		switch(item.get('tag')) {
			case 'input':
				if(item.get('type') == 'radio') {
					return this.setValueForRadio(item, value);
				} else {
					return this.setValueForInput(item, value);
				}
			case 'select':
				return this.setValueForInput(item, value);
			case 'textarea':
				return this.setValueForTextArea(item, value);
		}
	},
	setValueForInput: function(id, value) {
		$(id).set('value', value);
		return true;
	},
	setValueForRadio: function(id, value) {
		var radioObj = $(id);
		for(var i = 0; i < radioObj.length; i++) {
			radioObj[i].checked = false;
			if(radioObj[i].value == value.toString()) {
				return radioObj[i].checked = true;
			}
		}
		return false;
	},
	setValueForTextArea: function(id, value) {
		$(id).set('html', value);
		return true;
	}
});

