// XML HTTP Request object (works on most popupar browsers)
function HTTPConnector() {
  var xmlhttp=false;
  /*@cc_on @*/
  /*@if (@_jscript_version >= 5)
  // JScript gives us Conditional compilation, we can cope with old IE versions.
  // and security blocked creation of the objects.
  try {
    xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
  } catch (e) {
    try {
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (E) {
    xmlhttp = false;
    }
  }
  @end @*/
  if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
          try {
                  xmlhttp = new XMLHttpRequest();
          } catch (e) {
                  xmlhttp=false;
          }
  }
  if (!xmlhttp && window.createRequest) {
          try {
                  xmlhttp = window.createRequest();
          } catch (e) {
                  xmlhttp=false;
          }
  }
  return xmlhttp;
}

// Request data from the server
function HTTPRequest(_method,url,txt,success,failure) {
  var xmlhttp=HTTPConnector();
  xmlhttp.onreadystatechange=function() {
  	if(xmlhttp.readyState==4) {
  		if(xmlhttp.status && xmlhttp.status==200) {
	    	success(xmlhttp.responseText);
	    } else {
    		if(failure) failure(url, xmlhttp.status, xmlhttp.statusText);
    	}
    }
  }
  xmlhttp.open(_method,url,true);
  if(txt!==null && txt!==false && txt!='') {
  	xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  }
  xmlhttp.send(txt);
  return xmlhttp;
}

// Get data from data source. Async!
// Data is passed to the function in the fn argument.
// Function fn is never called if an error occours.
// Server response is evaluated as JavaScript.
// Sometimes ( ) pairs are required around JSON { } objects!
function read_datasource(_method, url, data, success, failure) {
	txt=data?encodeFormData(data):null;
	return HTTPRequest(
		_method, url, txt,
		function (response) {
		    try {
			  	if(response.substr(0,12)=='undefined /*') alert(response);
		      	data=eval(response);
		    } catch(e) {
		  	  	alert(
					'Error evaluating server response:\n'+e+
		  	  		'URL: '+url+'\n\nResponse:\n'+
		  	  		(
						(typeof(response)=='string' && response.length>500)?
		  	  	 		response.substr(0,500)+'...':response
					)
				);
		      	return false;
		    }
		  	success(data);
		    return true;
		},
		failure
	);
}

// Encode object keys and values as form data
function encodeFormData(data) {
	var pairs=[];
	var regexp=/%20/g;
	for(var name in data) {
		var value=data[name].toString();
		var pair=encodeURIComponent(name).replace(regexp,'+')+'='+encodeURIComponent(value).replace(regexp,'+');
		pairs.push(pair);
	}
	return pairs.join('&');
}
