var xml_request = false;

function makeXMLRequest(url, parameters) {
	xml_request = false;
	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		xml_request = new XMLHttpRequest();
		if (xml_request.overrideMimeType) {
			xml_request.overrideMimeType('text/plain');
		}
	} else if (window.ActiveXObject) { // IE
		try {
			xml_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xml_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	if (!xml_request) {
		alert('Cannot create XMLHTTP instance');
		return false;
	}
	xml_request.onreadystatechange = xml_handler;
	xml_request.open('GET', url + parameters);
	xml_request.send(null);
}

function xml_handler() {
	if(xml_request.readyState != 4) return false;
	if(xml_request.status != 200) return false;
	//alert("Got text: "+xml_request.responseText);
	var text = xml_request.responseText;
	if(!text) return false;
	var lines = text.split("\n");
	if(!lines) return false;
	for(var i=0; i<lines.length; i++){
		if(!lines[i].match(/^<(field|group) ([^>]+)>(.+)/)) continue;
		var type = RegExp.$1;
		var type_selector = RegExp.$2;
		var value = RegExp.$3;
		if(type == 'field'){
			fields[type_selector] = value;
		}
		else if(typeof(groups) == 'object'){
			groups[type_selector] = value;
		}
	}
	//alert(fields['email']);
}

makeXMLRequest('/user_information?requestor='+window.document.location+'&ignorecache=1', '');
//alert(xml_request.fields);
//setTimeout( "alert('email: '+fields['email']);", 5000);

function try_ajax() {
	this.attempt++;
	if(this.attempt > 20){
		clearInterval(this.tid);
	}
	if(fields.email){
		//alert('cached call to the_function()');
		clearInterval(this.tid);
		this.the_function();
	}
	//setTimeout(this.try_ajax(the_function),500);
}
function wait(){
	var myself = this;
	function callMethod() {
		myself.try_ajax();
	}
	this.tid = setInterval(callMethod, 500);
}
function Ajax(the_function){
	if(typeof(the_function) != 'function') return false;
	if(logged_out) return false;
	if( (typeof(fields) == 'object') && fields['id']){
		//if we aren't cached, we already have the user information, so immediately do the_function()
		//instead of starting an ajax call
		//alert('non-cached call to the_function()');
		the_function();
	}
	else {
		this.the_function = the_function;
		this.tid;
		this.attempt = 0;
		this.try_ajax = try_ajax;
		this.wait = wait;
		this.wait();
	}
}

