// Functions for asynchronous data exchange
// UGS Education Services
// Scott Sedam - 1/2006

function ajaxCall(dataURL, returnDiv, params) {

    var xmlHttpReq = init();
    xmlHttpReq.onreadystatechange = processRequest;
        
    function init() {
      if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
      } else if (window.ActiveXObject) {
        return new ActiveXObject("Microsoft.XMLHTTP");
      }
    }
    
    function processRequest () {
		// States are: 0 uninitialized
        //      1 loading
        //      2 loaded
        //      3 interactive
        //      4 complete		
      if (xmlHttpReq.readyState == 4) {
		  strResponse = xmlHttpReq.responseText;
		  webpartObj=document.getElementById(returnDiv);
		  switch (xmlHttpReq.status) {
			   // Page-not-found error
			   case 404:
					   alert('Error: Not Found. The requested URL could not be found.');
					   break;
			   // Display results in a full window for server-side errors
			   case 500:
					   alert('Server Error: Failed to load LMS data.');
					   //break;
					   webpartObj.innerHTML = strResponse;
			   default:
					  // Call JS alert for custom error or debug messages
					   if (strResponse.indexOf('Error:') > -1 || 
							   strResponse.indexOf('Debug:') > -1) {
							   alert(strResponse);
					   }
					   // Call the desired result function
					   else {
							//webpartObj.innerHTML = "";
							webpartObj.innerHTML = strResponse;
							document.body.style.cursor = "auto";
					   }
					   break;
		   }
      }
    }

    this.doGet = function() {
      xmlHttpReq.open("GET", dataURL+"?timeStamp="+new Date().getTime()+"&"+params, true);
      xmlHttpReq.send('');
    }
    
    this.doPost = function() {
      xmlHttpReq.open("POST", dataURL+"?timeStamp="+new Date().getTime(), true);
      xmlHttpReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      xmlHttpReq.send(params);
    }
}

function getData(dataURL,webpart,params,loadarea) {
	// show busy cursor, clear response div, and show loading graphic
	document.body.style.cursor = "progress";
	if (loadarea) {
 		document.getElementById(loadarea).innerHTML = "";
  		document.getElementById(loadarea).innerHTML = "Loading <img style='display:inline;' src='/images/loading2.gif' />";  		
	}
	// initialize new ajax request
	var req = new ajaxCall(dataURL, webpart, params);
	// send request and process
  	req.doGet();
}

function postData(dataURL,webpart,params) {
	// show busy cursor, clear response div, and show loading graphic
	document.body.style.cursor = "progress";
 	//document.getElementById(webpart).innerHTML = "";
  	//document.getElementById(webpart).innerHTML = "Loading <img style='display:inline;' src='/images/loading2.gif' />";  		
	// initialize new ajax request
	var req = new ajaxCall(dataURL, webpart, params);
	// send request and process
  	req.doPost();
}
