/* HttpRequestLib.js
   Wrapper functions for working with various flavors of XMLHTTP.
   This file was based on examples provided in AJAX Hacks by Bruce W. Perry */
   
var featureAlert=false;

/* httpRequest
  Wrapper function for constructing a request object.
  Parameters:
    reqType: The HTTP request type, such as GET or POST.
    url: The URL of the server program.
    asynch: Whether to send the request asynchronously or not.
    respHandle: The name of the function that will handle the response.
    data: If present, the data to send with a POST. */
function submitRequest(req,reqType,url,asynch) {
  // Submit request:
  if (req) {
    // if POST, get data from 5th arg:
    if (reqType.toLowerCase() == "post") {
      var args = arguments[4];
      if (args != null && args.length > 0) {
        sendPostRequest(req,url,asynch,args);
      } else {
        alert("POST operation requested, but no data was supplied.");
      }
    } else {
      sendGetRequest(req,url,asynch);
    }
  } else {
    if (!featureAlert) {
      featureAlert=true;
      alert("Your browser does not support all of this site's features.");
    }
  }
}

/* initRequest
   Initialize a request object and assign the response handler.
   Parameters:
   - respHandler: A reference to the response handler function. */
function initRequest(respHandler) {
  var req=null;
  //Mozilla-based browsers:
  if (window.XMLHttpRequest) {
    req = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    req = new ActiveXObject("Msxml2.XMLHTTP");
    if (!req)
      req = new ActiveXObject("Microsoft.XMLHTTP");
  }
  // Specify the function that will handle the response:
  if (req)
    req.onreadystatechange=respHandler;
  return req;
}

/* sendPostRequest
  Submit a POST request that was constructed with initRequest. */
function sendPostRequest(req,url,asynch,data) {
  try {
    req.open("POST",url,asynch);
    // Send posted data if provided:
    req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    req.send(arguments[4]);
  } catch (ex) {
    alert("The application cannot contact the server at this time. Please try again in a few seconds.\nError detail: " + ex.message);
  }
}

/* sendGetRequest
  Submit a GET request that was constructed with initRequest. */
function sendGetRequest(req,url,asynch) {
  try {
    req.open("GET",url,asynch);
    req.send(null);
  } catch (ex) {
    alert("The application cannot contact the server at this time. Please try again in a few seconds.\nError detail: " + ex.message);
  }
}

function FindNodeByAttribute(nodeList, attrName, attrValue) {
  var thisNode;
  var foundNode = null;
  for (var i=0; i<nodeList.length; i++) {
    thisNode = nodeList[i];
    if (thisNode.getAttribute(attrName) == attrValue) {
      foundNode = thisNode;
      break;
    }
  }
  return foundNode;
}
