/**
 * Returns true if AJAX is supported, false otherwise.
 */
function supportsAJAX() {
	return (window.XMLHttpRequest || window.ActiveXObject);
}


/**
 * This gets an XMLHttpRequest object in a cross-platform way.
 * By default the mime type is set to text/xml.
 *
 * @param xmlType true if you want to override the server's mime type to xml, false otherwise.  Default true.
 */
function getXmlHttpRequest(xmlType) {
  if (xmlType == null) {
    xmlType = true;
  }
  var http_request = false;
  if (window.XMLHttpRequest) { // Mozilla, Safari, ...
    http_request = new XMLHttpRequest();
    if (http_request.overrideMimeType && xmlType) {
      http_request.overrideMimeType('text/xml');
    }
  } else if (window.ActiveXObject) { // IE
    try {
      http_request = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        http_request = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e) {}
    }
  }
  return http_request;
}

/**
 * Returns true if the xmlHTTP object is in the middle
 * of doing a call
 * @param xmlhttp The XML-HTTP object
 * @return true if the object is working
 */
function callInProgress(xmlhttp) {
  if (!xmlhttp) {
    return false;
  }
  switch (xmlhttp.readyState) {
    case 1, 2, 3:
      return true;
    break;
    // Case 4 and 0
    default:
      return false;
    break;
  }
}

/**
 * Makes an asynch http call to the input url. Ignores the response.
 * @param xmlHttpRequest The XML-HTTP object
 * @param method The request method to use ("GET", "POST", etc.)
 * @param url The url to open
 * @param async true if this should be an asynchronous request, false otherwise.
 * @param callBackFunction The function to call when there is a state change in the request object. Note that this is not passed as a string literal.
 * @param body the body of the request
 */
function sendHttpRequest(xmlHttpRequest, method, url, async, callBackFunction, body) {
  xmlHttpRequest.open(method, url, async);
	xmlHttpRequest.onreadystatechange = callBackFunction;
	try {
		if (method != null && method.toUpperCase() == "POST") {
      xmlHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');      
      if (body == null) {
        // Squid and Firefox don't agree on how empty posts should work
        // so we put an empty body here so that they get along.
        body = "a";
      }
			xmlHttpRequest.send(body);
		}
		else {
			xmlHttpRequest.send(null);
		}
	}
	catch (e) {
		// probably server not initialized?
		if (callInProgress(xmlHttpRequest)) {
			xmlHttpRequest.abort();
		}
    throw e;
	}
}
