/**
 * Copyright 2006, Internet Broadcasting Systems. All Rights Reserved.
 * Version:   $Name: REL_2_40_3 $
 * ID:        $Id: AjaxForm.js,v 1.5 2007/01/08 21:49:58 breisinger Exp $
 */

/**
 * ibsys.AjaxForm
 *
 * Collects all form object values in {parent} and submits to {action}
 * using method {method}.  Does {onSuccess} with XMLHttpRequest result object. 
 * Expects {submitEl} to be the submit button for form. 
 */
using("ibsys");
ibsys.AjaxForm = function(parent,action,submitEl,onSuccess,method) {
	this.parent = $(parent);
	this.action = typeof action != "undefined" ? action : false;
	this.method = typeof method != "undefined" ? method : "get";
	this.onSuccess = typeof onSuccess == "function" ? onSuccess : function() {};
	this.goButton = $(submitEl) == null ? false : $(submitEl);
	this.inputs = this.collectInputs();
	
	var self = this;
	
	if(this.goButton) {
		Event.observe(this.goButton,"click",function() {
			var params = self.getInputValuesAsQueryString();
			self.sendAjaxQuery(params);
		},false);
	}
}
ibsys.AjaxForm.prototype = {
	queryString: "",
	collectInputs: function() {
		var self = this;
		var inputsArray = new Array();
		$A(this.parent.getElementsByTagName("*")).each(function(value) {
			thisNodeName = value.nodeName.toLowerCase();
			if(value != self.goButton && (thisNodeName == "select" || thisNodeName == "input" || thisNodeName == "textarea")) {
				inputsArray.push(value);
			}
		});
		return inputsArray;
	},
	sendAjaxQuery: function(params) {
		var self = this;
		this.requester = new Ajax.Request(
			self.action,
			{
				method: self.method,
				parameters: params,
				onComplete: self.onSuccess
			}
		);
	},
	getInputValuesAsQueryString: function() {
		var count = 0;
		var self = this;
		this.queryString = "";
		$A(this.inputs).each(function(value) {
			if(value.nodeName.toLowerCase() == "select") {
				if(value.options[value.options.selectedIndex].value != "") {
					if(count > 0) {
						self.queryString += "&";
					}
					count++;
					/* drop in value (strip space off front of string only) */
					var optionval = value.options[value.options.selectedIndex].value.replace(/^\s+|\s+$/g,'');
					
					self.queryString += value.id + "=" + encodeURIComponent(optionval);
				}
			} else if(value.nodeName.toLowerCase() == "input") {
				if(value.type.toLowerCase() == "text") {
					//text input "name"
					if(value.value) {
						if(count > 0) {
							self.queryString += "&";
						}
						count++;
						self.queryString += value.id + "=" + value.value;
					}
				}
			}
		});
		return this.queryString.replace(/\s/g,'%20');
	}
}

