/***************************************************************************
*   framework.zwo 1.1
*   Copyright 2002-2008 Daniel Wrana
*   http://www.edwiki.selbstlernarchitekturen.info
*   Distributed under the terms of the GNU General Public License v2 or later
****************************************************************************/

//*****************************************************************************
// ajax
//   Defines a object for making asynchronous HTTP GET and POST requests.
//-----------------------------------------------------------------------------
// Constructor:
//   ajax()
//     Creates a new instance of the HttpRequest object.
//     Notes: if you want to process the response, set the successCallback
//     property. To process errors on an unsuccessful request, set the
//     failureCallback property (see below).
//-----------------------------------------------------------------------------
// Properties:
//   successCallback
//     A function to be called when a GET or POST request completes
//     successfully (i.e., the HTTP status is "200 OK"). The function should
//     accept one argument which will be the HttpRequest object that made the
//     request
//   failureCallback
//     A function to be called when a GET or POST request completes
//     unsuccessfully (i.e., the HTTP status is anything other than "200 OK").
//     The function should accept one argument which will be the HttpRequest
//     object that made the request
//   status
//     The status of the response returned from a request. This will be an
//     HTTP status code. For example, a sucessful call returns 200.
//   statusText
//     The text associated with the status code. For example, the text for HTTP
//     status code 404 is "Object Not Found".
//   responseText
//     A string representing the data returned from a request.
//   responseXML
//     A DOM document object representing the XML returned from a request.
//-----------------------------------------------------------------------------
// Methods:
//   abort()
//     Aborts a request that is in currently progress.
//   setRequestHeader(name, value)
//     Sets the specified request header.
//   getRequestHeader(name)
//     Returns the value of the specified request header.
//   removeRequestHeader(name, value)
//     Removes the the specified request header.
//   clearRequestHeaders()
//     Removes all request headers.
//   request(data)
//     Performs an asynchronous POST request, passing the given data. Be sure
//     to set the "Content-Type" request header appropriately prior to calling
//     post().
//   getResponseHeader(name)
//     Returns the value of the named response header returned from a request.
//   getAllResponseHeaders()
//     Returns a string containing all the response headers returned from a
//     request.
//*****************************************************************************

// Define constants.
ajax.prototype.READY_STATE_UNINITIALIZED = 0;
ajax.prototype.READY_STATE_LOADING       = 1;
ajax.prototype.READY_STATE_LOADED        = 2;
ajax.prototype.READY_STATE_INTERACTIVE   = 3;
ajax.prototype.READY_STATE_COMPLETED     = 4;

// Define properties.
ajax.prototype.successCallback = null;
ajax.prototype.failureCallback = null;
ajax.prototype.username        = null;
ajax.prototype.password        = null;
ajax.prototype.requestHeaders  = new Array();
ajax.prototype.status          = null;
ajax.prototype.statusText      = null;
ajax.prototype.responseXML     = null;
ajax.prototype.responseText    = null;

// Define methods.
ajax.prototype.abort                   = ajaxAbort;
ajax.prototype.setRequestHeader        = ajaxSetRequestHeader;
ajax.prototype.clearRequestHeaders     = ajaxClearRequestHeaders;
ajax.prototype.request                 = ajaxRequest;
ajax.prototype.initiateRequest         = ajaxInitiateRequest;
ajax.prototype.getSimpleResponse       = ajaxGetSimpleResponse;
ajax.prototype.getTextResponse         = ajaxGetTextResponse;
ajax.prototype.getComplexResponse      = ajaxGetComplexResponse;
ajax.prototype.getResponseHeader       = ajaxGetResponseHeader;
ajax.prototype.getAllResponseHeaders   = ajaxGetAllResponseHeaders;
ajax.prototype.standardFailureCallback = ajaxStandardFailureCallback;
ajax.prototype.showAjaxHint            = ajaxShowHint;
ajax.prototype.hideAjaxHint            = ajaxHideHint;

//=============================================================================
// Contructor function.
//=============================================================================
function ajax() {
    var req;

   // Create the appropriate ajax object for the browser.
   this.xmlHttpRequest = null;
   if (window.XMLHttpRequest != null) {
     this.xmlHttpRequest = new window.XMLHttpRequest();
   } else if (window.ActiveXObject != null) {
     var versionList = ["MSXML2.XMLHttp.6.0", "MSXML2.XMLHttp.5.0", "MSXML2.XMLHttp.4.0", "MSXML2.XMLHttp.3.0",
                         "MSXML2.XMLHttp.2.0", "MSXML2.XMLHttp", "Microsoft.XMLHttp"];
     for (var i in versionList) {
       try {
         this.xmlHttpRequest = new ActiveXObject(versionList[i]);
       } catch (objError) {
         this.xmlHttpRequest = null;
       }
     }
  }

  // If we couldn't create one, display an error and exit
  if (this.xmlHttpRequest == null) {
    alert("Cannot create an XMLHttpRequest object. Please use a new version of Firefox, Mozilla, Netscape or Internet-Explorer");
    return;
  }
  this.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
}

//=============================================================================
// Methods.
//=============================================================================

function ajaxAbort() {
  this.xmlHttpRequest.abort();
}

function ajaxSetRequestHeader(name, value) {
  // If the header name already exists, replace the value.
  for (var i = 0; i < this.requestHeaders.length; i++) {
    var pair = this.requestHeaders[i].split("\n");
    if (pair[0].toLowerCase() == name.toLowerCase()) {
      this.requestHeaders[i] = name + "\n" + value;
      return;
    }
  }
  // Otherwise, add it as a new item.
  var n = this.requestHeaders.length;
  this.requestHeaders.push(name + "\n" + value);
}

function ajaxClearRequestHeaders() {
  this.requestHeaders = new Array();
}

function ajaxShowHint() {
  hintEl = top.document.getElementById('ajaxHint');
  hintStateEl = top.document.getElementById('ajaxHintState');
  hintEl.style.display = 'block';
  hintEl.style.top = (clickEventY - 5) + "px";
  hintEl.style.left = (clickEventX - 5) + "px";
  hintStateEl.innerHTML = "";
}

function ajaxHideHint() {
  hintEl.style.display = 'none';
}

function ajaxRequest(url, data) {
  this.initiateRequest(url, data);
}

/*
statusValues
0 - Fehler, result enthält eine Fehlermeldung
1 - allesOk, result enthält das korrekte Ergebnis der Abfrage
2 - Statusmeldung, der Wert ist bereits in der Datenbank vorhanden, kein Eintrag vorgenommen
*/
function ajaxGetSimpleResponse() {
  resp = this.responseXML;

  try {
    this.statusValue = resp.getElementsByTagName('status')[0].childNodes[0].nodeValue;
  } catch (e) {
    if (this.responseText == null) {
      //alertModal(emptyFunction, getLang("lang_pleasewait", 150));
    } else {
      alert("AjaxErrornoValidXML\r\n" + this.responseText);
    }
    return false;
  }
  try {
    this.resultValue = resp.getElementsByTagName('result')[0].childNodes[0].nodeValue;
  } catch (e) {
    this.resultValue = "";
  }
  if (this.statusValue == 0) alert('Error: ' + this.resultValue);
  return this.statusValue == 1 ? this.resultValue : false;
}

function ajaxGetComplexResponse() {
  resp = this.responseXML;
  try {
    this.statusValue = resp.getElementsByTagName('status')[0].childNodes[0].nodeValue;
  } catch (e) {
    if (this.responseText == null) {
      alertModal(emptyFunction, getLang("lang_pleasewait", 150));
    } else {
      alert("AjaxErrornoValidXML\r\n" + this.responseText);
    }
    return false;
  }
  return this.statusValue == 1 ? resp : false;
}

function ajaxGetTextResponse() {
  return this.responseText;
}

function ajaxGetResponseHeader(name) {
  return this.xmlHttpRequest.getResponseHeader(name);
}

function ajaxGetAllResponseHeaders() {
  return this.xmlHttpRequest.getAllResponseHeaders();
}

function ajaxStandardFailureCallback() {
  alertMessage = "";
  try {
    alertMessage += 'HTTP ' + formAjax.status + ' ' + formAjax.statusText;
  } catch(e) {}
  alert('Ajax Lookup failed. ' + alertMessage + '. Please Contact your Administrator');
  try {
    ajaxEle.value = storeValue;
  } catch (e) {}
  return false;
}

// the empty function is nessesary
function noReactionResponse () {
}

//=============================================================================
// Internal method to make the actual request.
//=============================================================================
function ajaxInitiateRequest(url, data, username, password) {
  // Clear all response fields.
  this.status       = null;
  this.statusText   = null;
  this.responseText = null;
  this.responseXML  = null;

  this.showAjaxHint();
  // Set up the callback functions.
  var refObj = this;
  this.xmlHttpRequest.onreadystatechange = function() {
    refObj.readyState = refObj.xmlHttpRequest.readyState;
    if (refObj.readyState == ajax.prototype.READY_STATE_COMPLETED) {
       refObj.hideAjaxHint();
       try {
         refObj.status       = refObj.xmlHttpRequest.status;
         refObj.statusText   = refObj.xmlHttpRequest.statusText;
         refObj.responseText = refObj.xmlHttpRequest.responseText;
         refObj.responseXML  = refObj.xmlHttpRequest.responseXML;
       } catch (e) {}
       if (refObj.status == 200) {
         if (refObj.successCallback != null) refObj.successCallback(refObj);
       } else {
         if (refObj.failureCallback != null) {
           refObj.failureCallback(refObj);
         } else {
           refObj.standardFailureCallback(refObj);
         }
       }
    }
  }
  // Initialize the request.
  this.xmlHttpRequest.open("POST", url, true, username, password);
  // Set request headers (this must be done after the request is opened).
  for (var i = 0; i < this.requestHeaders.length; i++) {
    var pair = this.requestHeaders[i].split("\n");
    this.xmlHttpRequest.setRequestHeader(pair[0], pair[1]);
  }
  // Start the request, passing any POST data.
  this.xmlHttpRequest.send(data);
}

