InternalXHR = {};
ExternalXHR = {};

ExternalXHR = function(xhr){
	
	var _xhr = xhr;
	var _content = "";	
	var _fetchurl = "http://feed.leibnizcenter.org/fetch.php";

	this.readyState = function(){return _xhr.readyState};
	this.xhr = function(){return _xhr};
	this.open = function(method, url){
		
		var urlparts = url.split("?");
		_content = "url="+ urlparts[0]+"&"+urlparts[1];
		_xhr.open("POST", _fetchurl);
		
		_xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); 
		
	/*Dit doe ik nu via de ExternalXHR.GET methode, met variabele headers (3de argument).
		_xhr.setRequestHeader('Accept', 'application/sparql-results+json'); */
		
		_xhr.setRequestHeader('Incoming-Method', "POST");
		_xhr.setRequestHeader('Outgoing-Method', method);
	}
	
	this.send = function(request_body){
		_xhr.send(_content + (_content != "" ? "&" : "" ) + request_body);
	}
	
	return this;
}

/*Class to do a simple GET request, with just a url, and callback to specified function */
ExternalXHR.GET = function(url, cb, headers){
	
	var _exhr = new ExternalXHR(new XMLHttpRequest());
	
	_exhr.open('GET',url);
	
	/*Set headers of the XHR*/
	if(typeof headers != 'undefined'){
		for(header in headers){
			_exhr.xhr().setRequestHeader(header,headers[header]);
			trace('Set header:: ' + header + ':' + headers[header])
		}
	}
	
	/*Perform callback when XHR is complete */
	setOnReadyStateChangeCallback(_exhr.xhr(), cb);

	_exhr.send();
	
	return _exhr.xhr();
}

/*Class to do a simple POST request, with just a url, and callback to specified function */
ExternalXHR.POST = function(url, postdata, cb){
	
	var _exhr = new ExternalXHR(new XMLHttpRequest());
	
	_exhr.open('POST',url);
	
	setOnReadyStateChangeCallback(_exhr.xhr(), cb);

	_exhr.send(postdata);
	
	return _exhr.xhr();
}

InternalXHR.POST = function(url, postdata, cb){
	var xhr = new XMLHttpRequest();
	xhr.open('POST', url, true);	
	
	//Send the proper header information along with the request
	xhr.setRequestHeader("Content-type", "text/xml");
	xhr.setRequestHeader("Content-length", postdata.length);
	xhr.setRequestHeader("Connection", "close");

	setOnReadyStateChangeCallback(xhr, cb);

	xhr.send(postdata);
	
	return xhr;
}

function setOnReadyStateChangeCallback(xhr, cb){
	var _callback;
	var _scope;
	if(cb['callback']){ _callback = cb.callback; } else { var _callback = cb; }
	if(cb['scope']){	_scope = cb.scope; } else { _scope = null; }
	
	xhr.onreadystatechange = function(){
		if(xhr.readyState == 4){
			if (xhr.status >= 200 && xhr.status < 300){
				_callback.call(_scope, xhr);
			}else{
				//Do something else
			}
		}
	}
}