// global xmlhttprequest object
var xmlHttp = false;

// constants
var REQUEST_GET  = 0;
var REQEST_POST  = 2;
var REQUEST_HEAD = 1;
var REQUEST_XML  = 3;

/*
instantiates a new xmlhttprequest object
@return xmlhttprequest object or false
*/

function getXMLRequester( ){
  var xmlHttp = false;
  // try to create a new instance of the xmlhttprequest object
  try{
    // Internet Explorer
    if( window.ActiveXObject ){
      for( var i = 5; i; i-- ){
        try{
          // loading of a newer version of msxml dll (msxml3 - msxml5) failed
          // use fallback solution
          // old style msxml version independent, deprecated
          if( i == 2 ){
            xmlHttp = new ActiveXObject( "Microsoft.XMLHTTP" );
          }
          // try to use the latest msxml dll
          else{
            xmlHttp = new ActiveXObject( "Msxml2.XMLHTTP." + i + ".0" );
          }
          break;
        }
        catch( excNotLoadable ){
          xmlHttp = false;
        }
      }
    }
    // Mozilla, Opera und Safari
    else if( window.XMLHttpRequest ){
      xmlHttp = new XMLHttpRequest();
    }
  }
  // loading of xmlhttp object failed
  catch( excNotLoadable ){
    xmlHttp = false;
  }
  return xmlHttp ;
}

/*
sends a http request to server
@param strSource, String, datasource on server, e.g. data.php
@param strData, String, data to send to server, optionally
@param intType, Integer,request type, possible values: REQUEST_GET, REQUEST_POST, REQUEST_XML, REQUEST_HEAD default REQUEST_GET
@param strData, Integer, ID of this request, will be given to registered event handler onreadystatechange', optionally
@return String, request data or data source
*/

function sendRequest( strSource, divID, strData, intType, noLoadingImg, intID){
    noLoadingImgStr = (noLoadingImg == true) ? "true" : "false";

    // previous request not finished yet, abort it before sending a new request
    if( xmlHttp && xmlHttp.readyState < 4)
    {
        setTimeout("sendRequest('"+strSource+"', '"+divID+"', '"+strData+"', '"+intType+"', '"+intID+"', "+noLoadingImgStr+")", 50);
        return;
        //xmlHttp.abort( );
        //xmlHttp = false;
    }

    //show loading-gif
    if(!noLoadingImg){
      var offsetHeight = parseInt(document.getElementById(divID).offsetHeight);
      if(offsetHeight && document.getElementById(divID).innerHTML && document.getElementById(divID).innerHTML != ""){
        changeStyle(divID, "height", offsetHeight+"px");
      }
      changeDivContent(divID, "<table style='width:100%; height:100%'><tr><td style='text-align:center; vertical-align:center; background-color:#FFFFFF'><img src='../images/ajax_process.gif' width='32' height='32' border='0' alt=''></td></tr></table>");
    }

    if( !strData )
        strData = '';

    // default type (0 = GET, 1 = xml, 2 = POST )
    if( isNaN( intType ) )
        intType = 0; // GET

    // create a new instance of xmlhttprequest object
    // if it fails, return
    if( !xmlHttp )
    {
        xmlHttp = getXMLRequester( );
        if( !xmlHttp )
            return;
    }

    // parse query string
    if( intType != 1 && ( strData && strData.substr( 0, 1 ) == '&' || strData.substr( 0, 1 ) == '?' ) )
        strData = strData.substring( 1, strData.length );

    // data to send using POST
    var dataReturn = strData ? strData : strSource;

    switch( intType )
    {
        case 1:    // xml
            strData = "xml=" + strData;
        case 2: // POST
            // open the connection
            xmlHttp.open( "POST", strSource, true );
            xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xmlHttp.setRequestHeader("Content-length", strData.length);
/*
            xmlHttp.onreadystatechange = function(){
              if(xmlHttp.readyState == 4){
                //if(xmlHttp.status == 200){
                  alert(xmlHttp.responseText);
                  document.getElementById(divID).innerHTML = xmlHttp.responseText;
                //}
              }
            }
            xmlHttp.send(strData);
            return;
*/
            break;
        case 3: // HEAD
            // open the connection
            xmlHttp.open( "HEAD", strSource, true );
            strData = null;
            break;
        default: // GET
            // open the connection
            var strDataFile = strSource + (strData ? '?' + strData : '' );
            xmlHttp.open( "GET", strDataFile, true );
            strData = null;
    }

    // set onload data event-handler
    xmlHttp.onreadystatechange = new Function( "", "processResponse(" + intID + ", '" + divID + "')" ); ;

    // send request to server
    xmlHttp.send(strData);    // param = POST data

    return dataReturn;
}

/*
process the response data from server
@param intID, Integer, ID of this response
*/

function processResponse( intID, divID )
{
    // status 0 UNINITIALIZED open() has not been called yet.
    // status 1 LOADING send() has not been called yet.
    // status 2 LOADED send() has been called, headers and status are available.
    // status 3 INTERACTIVE Downloading, responseText holds the partial data.
    // status 4 COMPLETED Finished with all operations.
    switch( xmlHttp.readyState )
    {
        // uninitialized
        case 0:
        // loading
        case 1:
        // loaded
        case 2:
        // interactive
        case 3:
            break;
        // complete
        case 4:
            // check http status
            if( xmlHttp.status == 200 )    // success
            {
                processData( xmlHttp, divID );
            }
            // loading not successfull, e.g. page not available
            else
            {
                if( window.handleAJAXError )
                    handleAJAXError( xmlHttp, intID );
                else
                    alert( "ERROR\n HTTP status = " + xmlHttp.status + "\n" + xmlHttp.statusText ) ;
            }
    }
}

function processData( xmlHttp, divID ){
  changeDivContent(divID, xmlHttp.responseText);
}

function changeDivContent(divID, content){
  document.getElementById(divID).innerHTML = content;
  /*parse javascript and execute it*/
  if(content.indexOf("<script type=\"text/javascript\">") != -1){
    var contentArr = content.split("<script type=\"text/javascript\">");
    var script = "";
    for(var i = 1; i < contentArr.length; i ++){
      var contentArr2 = contentArr[i].split("</script>");
      script += contentArr2[0];
    }
    script = script.replace(/<!--/g, "").replace(/\/\/-->/g, "").replace(/\n/g, "");
    //alert(script);
    eval(script);
  }
}

function sendAjaxForm(f, action, div, no_loading_img){
  var dataArr = new Array();
  if(!f || !f.elements){return}
  for(i = 0; i < f.elements.length; i ++){
    var e = f.elements[i];
    var type = e.type;
    if(type.toUpperCase().indexOf("SELECT") != -1){
      dataArr[dataArr.length] = e.name + "=" + e.options[e.selectedIndex].value;
    }
    else{
      switch(type.toUpperCase()){

        case "TEXT":
          dataArr[dataArr.length] = e.name + "=" + escape(e.value);
          break;

        case "TEXTAREA":
          dataArr[dataArr.length] = e.name + "=" + e.value;
          break;

        case "PASSWORD":
          dataArr[dataArr.length] = e.name + "=" + e.value;
          break;

        case "HIDDEN":
          dataArr[dataArr.length] = e.name + "=" + e.value;
          break;

        case "SUBMIT":
          if(e.name && e.name != "" && e.value && e.value != ""){
            dataArr[dataArr.length] = e.name + "=" + e.value;
          }
          break;

        case "BUTTON":
          break;

        case "RESET":
          break;

        case "RADIO":
          if(e.checked == true && e.value != ""){
            dataArr[dataArr.length] = e.name + "=" + e.value;
          }
          break;

        case "CHECKBOX":
          if(e.checked == true && e.value != ""){
            dataArr[dataArr.length] = e.name + "=" + e.value;
          }
          break;

        default:
          alert(e.type + "-Felder können zur Zeit noch nicht verarbeitet werden!");
      }
    }
  }
  if(!no_loading_img) var no_loading_img = false;
  ajaxRequest(action, div, dataArr.join("&"), 2, no_loading_img);
  return false;
}

var droppable_layers = new Array();
function ajaxRequest(strSource, divID, strData, intType, noLoadingImg, intID){
  switch(divID){
    case "address_groups":
      for(var i = 0; i < droppable_layers.length; i ++){
        Droppables.remove(droppable_layers[i]);
      }
      break;
  }
  sendRequest(strSource, divID, strData, intType, noLoadingImg, intID);
}

var ajaxDivArr = new Array();
function showAjaxDiv(strSource, divID, strData, intType, noLoadingImg, intID){
  changeStyle(divID, "visibility", "visible");
  changeStyle(divID, "left", posx+scrollX);
  changeStyle(divID, "top", posy+scrollY);
  sendRequest(strSource, divID);
  ajaxDivArr[ajaxDivArr.length] = divID;
}

function closeAjaxDiv(divID){
  changeStyle(divID, "visibility", "hidden");
  for(var i = 0; i < ajaxDivArr.length; i++){
    if(ajaxDivArr[i] == divID){
      ajaxDivArr[i] = null;
    }
  }
}
/** End AJAX functions **/