/**
 * Request handling Javascript functions used for the
 * EuroAlumni web application
 * (c) 2005 - 2007 Euro-Alumni e.V.
 **/

/** The request used to contact the server */
var req;

/** The server response as XML */
var serverXmlResponse;

/** The server response as text */
var serverResponseText;

/** The function to call when the xml response is available */
var functionToCallOnCompletion;

/** Simple lock to prevent multiple execution */
var alreadySending = false;


/**
 * Posts a GET request to the server, either using a hidden iframe or 
 * an XMLHTTPRequest (depending on the browser)
 * Does not wait for the answer
 * @param pageName the name of the page to call
 * @requestParamString the request parameters already assembled correctly
 *         (i.e. ?param1=foo&param2=bar)
 * @functionToCallOnCompletion the name of the function to call on 
 *         completion of the call
 */
function postGetRequest ( pageName, requestParamString, completionFunctionName ) {
	
	//Exit if there is already a request
	if ( alreadySending == true ) {
		return;
	}
	
	//Lock it
	alreadySending = true;
	
	//Add cachebuster to the request parameter string
	var cacheBuster = "&cb=" + ( new Date() ).getTime();

	//Record the function to call on completion
	functionToCallOnCompletion = completionFunctionName;

	//Get the correct thing and also do a very basic browser recognition
	if (window.XMLHttpRequest) {

    req = new XMLHttpRequest();

    // branch for IE/Windows ActiveX version
  } else if (window.ActiveXObject) {

    //Try to get first a newer, than an older IE version
    //of this object
    try {
      req = new ActiveXObject("Msxml2.XMLHTTP");
    } catch(e) {
      try {
          req = new ActiveXObject("Microsoft.XMLHTTP");
      } catch(e) {
          req = false;
      }
    }
  }
  
  //If we got something, use it
  if( req ) {

    //Build the URL
    var urlToCall = pageName + requestParamString + cacheBuster;

		//From here on, IE works the same
		req.open("GET", urlToCall, true);
		req.onreadystatechange = callback;
		req.setRequestHeader( "Content-Type", "text/xml;charset=UTF-8" );
		req.setRequestHeader( "Accept-Charset", "UTF-8" );
		req.send(null);

		var test = "do something else";
		return;
	}

  //Does not support it, bail out here (silently!)
  //window.setTimeout( "alert('Sorry, your browser does not support this function!');", 50 );
	return true;
}


/**
 * Posts a POST request to the server, either using a hidden iframe or 
 * an XMLHTTPRequest (depending on the browser)
 * Does not wait for the answer
 * @param pageName the name of the page to call
 * @requestParamString the request parameters already assembled correctly
 *         (i.e. ?param1=foo&param2=bar)
 * @functionToCallOnCompletion the name of the function to call on 
 *         completion of the call
 */
function postPostRequest ( pageName, requestParamString, completionFunctionName ) {
	
	//Exit if there is already a request
	if ( alreadySending == true ) {
		return;
	}
	
	//Lock it
	alreadySending = true;
	
	//Add cachebuster to the request parameter string
	var cacheBuster = ";cbjs=" + ( new Date() ).getTime();

	//Record the function to call on completion
	functionToCallOnCompletion = completionFunctionName;

	//Get the correct thing and also do a very basic browser recognition
	if (window.XMLHttpRequest) {

    req = new XMLHttpRequest();

    // branch for IE/Windows ActiveX version
  } else if (window.ActiveXObject) {

    //Try to get first a newer, than an older IE version
    //of this object
    try {
      req = new ActiveXObject("Msxml2.XMLHTTP");
    } catch(e) {
      try {
          req = new ActiveXObject("Microsoft.XMLHTTP");
      } catch(e) {
          req = false;
      }
    }
  }
  
  //If we got something, use it
  if( req ) {

    //Build the URL
    var urlToCall = pageName + cacheBuster;

		//From here on, IE works the same
		req.open("POST", urlToCall, true);
		req.onreadystatechange = callback;
		req.setRequestHeader( "Accept-Charset", "UTF-8" );
		req.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded; charset=UTF-8" );
		req.send( requestParamString );

		var test = "do something else";
		return;
	}

  //Does not support it, bail out here (silently!)
	return true;
}


/**
 * Callback function gets called if the XmlHttpRequest object
 * changes its state (i.e. also when it is finished)
 */
function callback() {

		//Exit if req is null
		if ( req == null ) {
			return;
		}
		
		//Check the result
    if (req.readyState == 4) {
        if (req.status == 200) {

						//Parse the messages
						//parseMessages();            
						
						//Extract the content
						serverXmlResponse = req.responseXML;
						serverResponseText = req.responseText;
						
            //Call the defined function if it exists
            if ( (functionToCallOnCompletion != null) && (functionToCallOnCompletion != "undefined") ) {
            
            	//Add the brackets if they do not exist
            	if ( functionToCallOnCompletion.indexOf("(") < 0 ) {
            		functionToCallOnCompletion = functionToCallOnCompletion+"()";
            	}
            
            	//Call it
            	window.setTimeout( functionToCallOnCompletion, 20 );
            }

						//Unlock						
						alreadySending = false;
        }
    }
    return;
}

function parseMessages() {

   //Extract the response
    var xmessage = req.responseXML.getElementsByTagName("message")[0];
    serverXmlResponseText = xmessage.childNodes[0].nodeValue;
    
    alert("Response received: "+serverXmlResponseText+" / Function: "+functionToCallOnCompletion);
}

/**
 * Function that does nothing to use if you do need a return value
 */
function doNothing() {
	return true;
}


/**
 * Posts a request to the server in a separate thread, either using a 
 * hidden iframe or  an XMLHTTPRequest (depending on the browser)
 * Does not wait for the answer
 * @param pageName the name of the page to call
 * @requestParamString the request parameters already assembled correctly
 *         (i.e. ?param1=foo&param2=bar)
 * @functionToCallOnCompletion the name of the function to call on 
 *         completion of the call
 */
function asyncGetRequest ( pageName, requestParamString, functionToCallOnCompletion ) {

	setTimeout( "postGetRequest(\""+pageName+"\", \""+requestParamString+"\", \""+functionToCallOnCompletion+"\")", 13);
	return;
}


/**
 * Posts all elements of a specific form
 * to a specific page using XmlHTTPRequest
 * @param pageName the name of the page to call
 * @param formName the form from which to extract the
 *        parameters
 * @param the webaction that should be used instead of the one
          in the form
 */
function postFormBackground ( pageName, formName, webAction ) {

	//Get the form
	var thisForm = document.getElementById( formName );

	//Build the String to send
	var requestBody;

	for( var t=0; t < thisForm.elements.length; t=t+1 ) {
		if ( "webaction" == thisForm.elements[t].name  ) {
			requestBody = requestBody + "&webaction="+webAction;
		} else {
			requestBody = requestBody + "&"+encodeURIComponent( thisForm.elements[t].name )+"="+encodeURIComponent( thisForm.elements[t].value );
		}
	}

	if (window.XMLHttpRequest) {

		//Add cachebuster to the request parameter string
		var cacheBuster = "&cb=" + ( new Date() ).getTime();

		xmlhttp = new XMLHttpRequest();
		xmlhttp.open("POST", pageName + cacheBuster, true);
		xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
		xmlhttp.send(requestBody);
		return;
	}
}


/**
 * Returns a value from an xml node or an empty
 * string if the node cannot be found. The node is
 * searched in the supplied root node, the first text node
 * child of the first node with the correct name found 
 * is returned.
 * @param root the XML node in which to search
 * @param nodeName the name of the node to search for
 *        (that contains the text to return)
 * @return a String that contains the text or an empty
 *         String if nothing can be found
 **/
function getValueFromXmlNode( root, nodeName ) {

  //Return an empty string if root or nodeName do not exist
  if ( !root || !nodeName || (root === null) || (nodeName === null) ) {
    return "";
  }
  
  //Get the node in question
  var nodesFound = root.getElementsByTagName( nodeName );
  if ( nodesFound.length > 0 ) {

    var nodeFound = nodesFound[0];
    if ( nodeFound && nodeFound.hasChildNodes() ) {

      var textNode = nodeFound.firstChild;
      if ( textNode && ( textNode !== null ) ) {
        return textNode.nodeValue;
      }
    }
  }
  
  //Return an empty string
  return "";
}