// Mille et Un Rêves AJAX aka MAJAX
// by zemax - 2005
// http://www.1001reves.com
// Feel free to use, modify, distribute...

function majax(){
	var self = this; // bug fix
	
	this.encodeURIString = true;
	
	this.onNoAJAX = function() {};
	this.onOpen = function() {};
	this.onSent = function() {};
	this.onLoading = function() {};
	this.onLoad = function() {};
	
	this.init = function() {
		try {
			this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e) {
			try {
				this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (oc) {
				this.xmlhttp = null;
			}
		}
		
		if ((!this.xmlhttp) && (typeof XMLHttpRequest != "undefined")) {
			this.xmlhttp = new XMLHttpRequest();
		}
		
		if (!this.xmlhttp) { // no AJAX.
			this.failed = true;
			
			this.onNoAJAX();
		}
		else {
			this.failed = false;
		}
	};
	
	this.encodeURLString = function(string) {
		varArray = string.split('&');
		for (var i=0; i<varArray.length; i++){
			urlVars = varArray[i].split('=');
			if (urlVars[0].indexOf('amp;') != -1) {
				urlVars[0] = urlVars[0].substring(4);
			}
			urlVars[0] = encodeURIComponent(urlVars[0]);
			urlVars[1] = encodeURIComponent(urlVars[1]);
			varArray[i] = urlVars.join("=");
		}
		return varArray.join('&');
	};
	
	this.send = function(url, vars, method) {
		if (!this.failed) {
			if (typeof(vars) == "undefined") {
				vars = "";
			}
			
			if (typeof(method) == "undefined") {
				method = "GET";
			}
			
			if ((vars) && (this.encodeURIString)) {
				vars = this.encodeURLString(vars);
			}
			
			if (method == "GET") {
				this.xmlhttp.open(method, url + "?" + vars ,true);
				vars = null;
			}
			else if (method == "POST") {
				this.xmlhttp.open(method, url ,true);
				this.xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			}
			else {
				this.xmlhttp.open(method, url ,true);
			}
			
			this.xmlhttp.onreadystatechange = function() {
				switch (self.xmlhttp.readyState) {
					case 1: // Connection open
						self.onOpen();
						break;
					case 2: // Data sent
						self.onSent();
						break;
					case 3: // Loading every 4096 bytes
						self.onLoading();
						break;
					case 4: // Completed.
					 	self.responseXML = self.xmlhttp.responseXML;
						self.response = self.xmlhttp.responseText;
						
						self.onLoad();
						
						if (self.element) {
							var elt = document.getElementById(self.element);
							elt.innerHTML = "";
							elt.innerHTML = self.response;
						}
						break;
				}
			};

			this.xmlhttp.send(vars);
		}
	};
}
