//moo.ajax.js v1.1 xp

Ajax = new Class({

	setOptions: function(options) {
		this.options = {
			method: 'post',
			postBody: '',
			async: true,
			onComplete: null,
			update: null
		};
		Object.extend(this.options, options || {});
	},

	initialize: function(url, options){
		this.setOptions(options);
		this.url = url;
		this.transport = this.getTransport();
		this.request();
	},

	request: function(){
		this.transport.open(this.options.method, this.url, this.options.async);
		this.transport.onreadystatechange = this.onStateChange.bind(this);
		if (this.options.method == 'post') {
			this.transport.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
			if (this.transport.overrideMimeType) this.transport.setRequestHeader('Connection', 'close');
		}
		if (this.options.postBody.tagName) this.options.postBody = $(this.options.postBody).toQueryString();
		else if (typeof this.options.postBody == 'object') this.options.postBody = Object.toQueryString(this.options.postBody);
		this.transport.send(this.options.postBody);
	},

	onStateChange: function(){
		if (this.transport.readyState == 4 && this.transport.status == 200) {
			if (this.options.update) setTimeout(function(){$(this.options.update).innerHTML = this.transport.responseText;}.bind(this), 10);
			if (this.options.onComplete) setTimeout(function(){this.options.onComplete(this.transport);}.bind(this), 15);
			//this.transport.onreadystatechange.empty();
		}
	},

	getTransport: function() {
		if (window.XMLHttpRequest) return new XMLHttpRequest();
		else if (window.ActiveXObject) return new ActiveXObject('Microsoft.XMLHTTP');
		else return false;
	}

});

Element.extend({

	toQueryString: function(){
		var queryString = '';
		$c(this.getElementsByTagName('*')).each(function(el){
			var name = el.name || false;
			var value = false;

			if (el.tagName.toLowerCase() == 'select'){
				value = el.getElementsByTagName('option')[el.selectedIndex].value;
			} else if (el.tagName.toLowerCase() == 'input' && (el.getAttribute('type') == 'checkbox' || el.getAttribute('type') == 'radio')){
				if (el.checked) value = el.value;
			}
			else if ((el.tagName.toLowerCase() == 'input' && 
				(el.getAttribute('type') == 'hidden' || el.getAttribute('type') == 'text' || el.getAttribute('type') == 'password')) || 
				el.tagName.toLowerCase() == 'textarea'){
					value = el.value;
			}
			if (name && value) queryString += encodeURIComponent(name)+'='+encodeURIComponent(value)+'&';
		});
		return queryString.substring(queryString.length-1, 0);
	}

});