//var Ajax_ReadyStates = ['UNINITIALIZED', 'LOADING', 'LOADED', 'INTERACTIVE', 'COMPLETED'];
// stolen/modified from wounded
var ajax_error_message = '<span class="waiting_error">Error retrieving Information.</span>';
function do_with_ajax(url, data, func){
	try{
		var xmlhttp = new_ajax_object();
		//if( xmlhttp.overrideMimeType && options.reponse ) xmlhttp.overrideMimeType('text/xml');
		xmlhttp.open((data ? 'POST' : 'GET'), url, true);
		xmlhttp.onreadystatechange = function(){
				try{ 
					if( ajaxed(xmlhttp) ){ func(xmlhttp); }
				}catch(e){ func(null, e); }
				//xmlhttp.onreadystatechange = null; // ie memory leaks from the activex?
			};
		//xmlhttp.setRequestHeader('Content-Type', options.type);
		xmlhttp.setRequestHeader("X-Requested-With", "XMLHttpRequest");
		xmlhttp.send(data);
		return true;
	}catch(e){ func(null, e); }
	return false;
}

function fill_with_ajax(element, url, data){
	do_with_ajax(url, data, function(xmlhttp, e){ return fill_with_ajax_response(element, xmlhttp, e); });
}

function fill_with_ajax_response(element, xmlhttp, e){
	return element.innerHTML = xmlhttp ? xmlhttp.responseText : ajax_error_message;
}

function new_ajax_object(){
	var xmlhttp;
	try{ xmlhttp = new XMLHttpRequest();   /* please */    }catch(e){
	try{ xmlhttp = new ActiveXObject('Msxml2.XMLHTTP');    }catch(e){
	try{ xmlhttp = new ActiveXObject('Microsoft.XMLHTTP'); }catch(e){ return false; }}}
	return xmlhttp;
}
function ajaxed(xmlhttp){
	if( xmlhttp.readyState == 4 ){
		if( xmlhttp.status == 200)
			return true;
		else{
			var url = xmlhttp.getResponseHeader('Location');
			if( xmlhttp.status == 409 && url ){ // 409 Conflict
				location.href = url;
				return false;
			}else
				throw('Server returned error status ' + xmlhttp.status.toString());
		}
	}else
		return false;
}

var loading_icon;
function place_holder(txt, attributes){
	var tmp = document.createElement('div');
	if( attributes )
		for( var a in attributes )
			tmp.setAttribute(a, attributes[a]);
	tmp.className = 'waiting';
	if( ! loading_icon ){
		loading_icon = new Image();
		loading_icon.src = '/images/icons/spinner.gif';
		loading_icon.className = 'loading';
	}
	tmp.appendChild(loading_icon);
	tmp.appendChild(document.createTextNode(txt || 'retrieving information...'));
	return tmp;
}
