

// ajax request object
function ajax() {
	
	// execute AJAX request
	this.request = function(url, url_params, callback, passthru) { 
	
		if (req = init_req()) {
			req.onreadystatechange = function() { req_callback(req, url, callback, passthru); };
			req.open('POST', url, true);
			req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			
			//alert(encode_params(url_params));
			
			req.send(encode_params(url_params));			
		
		} else { alert("Could not initialize AJAX request object."); }
	
	}
	
	// returns URL encoded query string
	// ** doesn't currently encode arrays... **
	function encode_params(params) {				
		if (params) {
			var qry = "";
			for (key in params) { qry += encodeURIComponent(key) + "=" + encodeURIComponent(params[key]) + "&"; }
			return qry.substr(0, qry.length-1);		
		
		} else return false;		
	}
		
	// handles the request callback
	function req_callback(req, url, callback, passthru) {
	
		if (req.readyState == 4) {
            if (req.status == 200) {
				if (typeof(callback) == "function")
					callback(req.responseText, passthru);
            } else {
				
                alert('There was a problem receiving the request:' + req.status);
            }
        }
	
	}	

	// initializes and returns an http request object
	function init_req() {
	
		var req;
		
		// mozilla, safari, etc.
		if (window.XMLHttpRequest) { 
			req = new XMLHttpRequest(); 
		}	
		// IE 8
		else if (window.XDomainRequest) { 
			var req = new XDomainRequest(); 
		}	
		// other IE
		else if (window.ActiveXObject) {
				
			try { req = new ActiveXObject("Msxml2.XMLHTTP"); }		
			catch(e){			
				try { req = new ActiveXObject("Microsoft.XMLHTTP"); } 
				catch(e) { }
			}
		}
			
		if (req) return req;
		else { return false; }
	
	}
	
}


