/**
*	asyncfilter.js
*
*	Provide a transparent mechanism for dynamically
*	filtering a data list.
*
*	@author Dave Liotta
*	@copyright &copy;2006 Leedom and Associates, LLC
*	@created June 25th, 2009
*/

/**
*	AsyncFilter class
*/
function AsyncFilter(FormId, ContentId, ContentService) {

	var SearchFormObj = null;
	var ContentObj = null;
	var InputItems = null;

	this.Initialize = function() {
		InputItems = new Array();

		AcquireObjects();
		TraverseNodeTree(SearchFormObj);
		ApplyEventListeners();
	}

	this.Destroy = function () { RemoveEventListeners(); }

	function AcquireObjects() {
		SearchFormObj = document.all ? document.all[FormId] : document.getElementById ? document.getElementById(FormId) : null;
		ContentObj = document.all ? document.all[ContentId] : document.getElementById ? document.getElementById(ContentId) : null;
	}

	function TraverseNodeTree(AnObject) {
		if ( AnObject != null ) {
			for (var i=0; i < AnObject.childNodes.length; i++) {
				CurrentNode = AnObject.childNodes[i];
				switch ( CurrentNode.nodeName.toLowerCase() ) {
					case "input":
						if ( CurrentNode.type == "submit" ) CurrentNode.style.display = "none";
						else InputItems.push(CurrentNode);
						break;
					case "select":
					case "textarea":
						InputItems.push(CurrentNode);
						break;
					default:
						if ( CurrentNode.childNodes.length > 0 ) TraverseNodeTree(CurrentNode);
				}
			}
		}
	}

	function ApplyEventListeners() {
		if ( InputItems != null ) {
			for (var i=0; i < InputItems.length; i++) {
				attachEventListener(InputItems[i], "change", ItemChanged, false);
			}
		}
	}

	function RemoveEventListeners() {
		if ( InputItems != null ) {
			for (var i=0; i < InputItems.length; i++) {
				detachEventListener(InputItems[i], "change", ItemChanged, false);
			}
		}
	}

	function ItemChanged(event) {
		function CallBack(AResponse) {
			if (ContentObj) ContentObj.innerHTML = AResponse.responseText;
		}

		AJAXQuery(ContentService + "?" + AcquireGetParams(), null, CallBack);
	}

	function AcquireGetParams() {
		if ( InputItems != null ) {
			Params = new Array();
			for (var i=0; i < InputItems.length; i++) {
				Params.push(encodeURIComponent(InputItems[i].name) + "=" + encodeURIComponent(InputItems[i].value));
			}
			return Params.join("&");
		}

		return "";
	}

	return true;

}
