//based on prototype's ajax class
//to be used with prototype.lite, moofx.mad4milk.net.
function statusbox(){
	$('istatus').innerHTML = '<img src="/images/loading.gif" alt="" />';
}

ajax = Class.create();
ajax.prototype = {
	initialize: function(url, options){
		this.transport = this.getTransport();
		this.postBody = options.postBody || '';
		this.method = options.method || 'post';
		this.onLoading = options.onLoading || null;		
		this.onFailure = options.onFailure || null;		
		this.onComplete = options.onComplete || null;
		this.update = $(options.update) || null;
		this.evalScripts = options.evalScripts || false;
		this.request(url);
	},

	request: function(url){
		this.transport.open(this.method, url, true);
		this.transport.onreadystatechange = this.onStateChange.bind(this);
		if (this.method == 'post') {
			statusbox();
			this.transport.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
			if (this.transport.overrideMimeType) this.transport.setRequestHeader('Connection', 'close');
		}
		this.transport.send(this.postBody);
	},

	onStateChange: function(){
		if (this.transport.readyState == 4 && this.transport.status == 200) {
			if (this.onComplete) 
				setTimeout(function(){this.onComplete(this.transport);}.bind(this), 10);
			if (this.update) {
			    var match    = new RegExp('(?:<script.*?>)((\n|.)*?)(?:<\/script>)', 'img');
			    var response = this.transport.responseText.replace(match, '');
			    var scripts  = this.transport.responseText.match(match);
			
				setTimeout( function(){
					this.update.innerHTML = response;
				}.bind(this), 10);
				
			    if (this.evalScripts && scripts) {
					match = new RegExp('(?:<script.*?>)((\n|.)*?)(?:<\/script>)', 'im');
					setTimeout((function() {
						for (var i = 0; i < scripts.length; i++)
							eval(scripts[i].match(match)[1]);
					}).bind(this), 10);				
				}
			}
			this.transport.onreadystatechange = function(){};
		} else if ( this.transport.readyState != 1 && 
				   this.transport.status != undefined && this.transport.status != 0 
				   && ( this.transport.status < 200 || this.transport.status >= 300 ) ) {
			if ( this.onFailure ) {
				setTimeout(function(){this.onFailure();}.bind(this), 10);
			}
			this.transport.onreadystatechange = function(){};
		}
	},

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