/* timeout-setting for IE */
var timeout=20;
var requestRunning=false;

prepareRelUrl = function( url ) {
  if ( url.indexOf("http://") == 0 || url.indexOf("https://") == 0 ) {
    url = url.substring( url.indexOf("://") + 3 );
    url = url.substring( url.indexOf("/") );
  }
  return url;
}


encodeParamAjax = function( input ) {
 input = input.replace(/%/g ,"%25");
 input = input.replace(/\n/g,"%0D");
 input = input.replace(/\$/g,"%24");
 input = input.replace(/&/g,"%26");
 input = input.replace(/\+/g,"%2B");
 input = input.replace(/,/g ,"%2C");
 input = input.replace(/\//g,"%2F");
 input = input.replace(/:/g ,"%3A");
 input = input.replace(/;/g ,"%3B");
 input = input.replace(/=/g ,"%3D");
 input = input.replace(/\?/g,"%3F");
 input = input.replace(/@/g ,"%40");
 input = input.replace(/ /g ,"%20");
 input = input.replace(/</g ,"%3C");
 input = input.replace(/>/g ,"%3E");
 input = input.replace(/#/g ,"%23");
 input = input.replace(/"/g ,"%22");
 input = input.replace(/{/g ,"%7B");
 input = input.replace(/}/g ,"%7D");
 input = input.replace(/\|/g,"%7C");
 input = input.replace(/\\/g,"%5C");
 input = input.replace(/\^/g,"%5E");
 input = input.replace(/~/g ,"%7E");
 input = input.replace(/\[/g,"%5B");
 input = input.replace(/\]/g,"%5D");
 input = input.replace(/`/g ,"%60");
 return(input);
}

/* create new XMLHttpRequest */
createXMLHttpRequest = function() { 
  var result = null;
  if (typeof XMLHttpRequest != 'undefined') {
      result = new XMLHttpRequest();
  }
  if (!result) {
      // Internet Explorer 6 und älter
      try {
          result  = new ActiveXObject("Msxml2.XMLHTTP");
      } catch(e) {
          try {
              result  = new ActiveXObject("Microsoft.XMLHTTP");
          } catch(e) {
              result  = null;
          }
      }
  }
  return result;
}


/* reload images (IE) */
reloadImages = function( element ) {
  images = document.getElementById( element ).getElementsByTagName('img');
  for ( i = 0; i < images.length; i++ ) {
    tmpImg = new Image();
    tmpImg.src = images[i].src;
    images[i].src = tmpImg.src; 
  }
  inputImgs = document.getElementById( element ).getElementsByTagName('input');
  for ( i = 0; i < inputImgs.length; i++ ) {
    if ( inputImgs[i].type == 'image' ) {
      tmpImg = new Image();
      tmpImg.src = inputImgs[i].src;
      inputImgs[i].src = tmpImg.src; 
    }
  }

}

var requests = new Array();

XMLRequest = function( url, element, name, showLoader, post, poststr ) {
  this.url = url;
  this.post = post;
  this.poststr = poststr;
  this.element = element;
  this.inProgress=false;
  this.done=false;
  this.ref = name;
  this.loadingInt = false;
  this.checkInt = false;
  this.request = createXMLHttpRequest();
  this.arrayPos = -1;
  this.showLoad = showLoader;
  if ( this.request == null ) { window.location.replace(error500Page); return; }
  this.obj = document.getElementById(this.element);
  if ( this.obj == null ) { window.location.replace(error500Page); return; }

  this.checkSuccess = function() {
    if ( this.getReadyState() <= 0 ) {
      this.cancel();
    }
  }

  this.cancel = function() {
    if ( this.loadingInt != false ) {
      clearInterval( this.loadingInt );
      this.loadingInt = false;
    }
    if ( this.checkInt != false ) {
      clearInterval( this.checkInt );
      this.checkInt = false;
    }
    if ( this.request ) this.request.abort();
    this.removeWaitLayer();
    document.getElementsByTagName('body')[0].style.cursor="auto";
  }

  this.createWaitLayer = function() {
    if ( this.getReadyState() <= 0 ) return;
    if ( this.loadingInt != false ) { clearInterval(this.loadingInt); loadingInt = false; }
    tmpObj = this.obj;
    for ( var x = 0, y = 0; tmpObj != null; x+=tmpObj.offsetLeft, y+=tmpObj.offsetTop, tmpObj=tmpObj.offsetParent );
    height  = this.obj.offsetHeight;
    width   = this.obj.offsetWidth;
     
    leftPos = x;
    topPos  = y;    

    var loaderContent = document.createElement("div");
    var loaderClass = document.createAttribute("class");
    loaderClass.nodeValue = "loaderContent";
    loaderContent.setAttributeNode(loaderClass);

    var img   = document.createElement("img");
    var src   = document.createAttribute("src");
    src.nodeValue = ajaxLoaderImage;
    var border   = document.createAttribute("border");
    border.nodeValue = "0";
    img.setAttributeNode(src);
    img.setAttributeNode(border);
  
    loaderContent.appendChild(img);

    var layer = document.createElement("div");
    
    var styleNode = document.createAttribute("class");
    styleNode.nodeValue = "ajaxLoader contentBackground";
  
    loaderContent.style.visibility = "hidden";

    var idNode = document.createAttribute("id");
    idNode.nodeValue = this.ref;
    layer.setAttributeNode(styleNode); 
    layer.setAttributeNode(idNode); 


    layer.appendChild(loaderContent);
    if ( mz ) {
      layer.style.left   = leftPos + 'px';
      layer.style.top    = topPos  + 'px';
    }
    else {
      layer.style.pixelLeft   = leftPos;
      layer.style.pixelTop    = topPos;
    }
    layer.style.width  = width   + 'px';
    layer.style.height = height  + 'px';
    document.getElementsByTagName('body')[0].appendChild(layer);

    var hLay = document.getElementById(this.ref);
    var contHeight = 0;
    var contWidth = 0;
    for ( i = 0; i < hLay.childNodes.length; i++ ) {
      contHeight += hLay.childNodes[i].offsetHeight;
      if ( contWidth < hLay.childNodes[i].offsetWidth ) contWidth = hLay.childNodes[i].offsetWidth;
    }

    if ( (contHeight + 10) > height ) {
      height = contHeight + 10;
      layer.style.height = height  + 'px';
    }

    minVisY = ( mz ) ? window.pageYOffset : document.documentElement.scrollTop;
    maxVisY = ( mz ) ? window.innerHeight  + window.pageYOffset : document.documentElement.clientHeight + document.documentElement.scrollTop;
    min = ( topPos < minVisY ) ? 0 : (topPos - minVisY);
    max = (mz) ? window.innerHeight : document.documentElement.clientHeight;
    if ( (topPos + height) <= maxVisY ) {
      max -= (maxVisY - ( topPos + height ));
    }

    topVis = ( minVisY < topPos && maxVisY > topPos ) ? true : false;
    botVis = ( minVisY < (topPos + height) && maxVisY > (topPos + height) ) ? true : false;
    layVis = ( minVisY < (topPos + height) ) ? true : false;

    space = max - min;

    var contTop = 0;

    if ( layVis && height > contHeight  ) {
      if ( topVis ) {
        contTop = ((space / 2) - (contHeight / 2));
      }
      else {
        contTop = (((space / 2) - (contHeight / 2)) + (minVisY - topPos));
      }
    }
    
    var contLeft = Math.round(( width / 2 ) - (contWidth / 2));
    if ( mz ) {
      loaderContent.style.left = contLeft + 'px';
      loaderContent.style.top  = contTop + 'px'; 
    }
    else {
      loaderContent.style.pixelLeft = contLeft;
      loaderContent.style.pixelTop  = contTop; 
    }
    loaderContent.style.visibility = "visible";

  }

  this.removeWaitLayer = function() {
    obj = document.getElementById(this.ref);
    if ( obj != null ) {
      document.getElementsByTagName('body')[0].removeChild(obj);
    }
  }
  
  this.execute = function() {
    this.inProgress = true;
    this.calcArrayPos();
    if ( this.arrayPos >= 0 ) {

      this.url = prepareRelUrl(url);

      if (typeof(XMLHttpRequest) == "undefined" || ie) 
      {
        tmpDate = new Date();
        if ( this.post ) {
          if ( this.poststr != null && this.poststr != ''  ) { this.poststr += "&"; }
          this.poststr += "noCache=" + tmpDate.getTime() + ""; 
        }
        else {
          if ( this.url.indexOf("?") != -1 ) this.url += "&noCache=" + tmpDate.getTime() + "";
          else this.url += "?noCache=" + tmpDate.getTime() + "";
        }
      }
      document.getElementsByTagName('body')[0].style.cursor="wait";
      if ( this.post ) {
        this.request.open('POST', this.url, true);
        this.request.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
        this.request.setRequestHeader("Content-length", this.poststr.length);
        this.request.setRequestHeader("Connection", "close");
      }
      else {
        this.request.open('GET', this.url, true);
        this.request.setRequestHeader('Content-Type', 'text/xml; charset=UTF-8'); 
      }
      this.request.setRequestHeader('Cache-Control', 'no-cache');
      if ( this.post ) this.request.send(this.poststr);
      else this.request.send(null);
      if ( this.showLoad ) this.loadingInt = setInterval("requests[" + this.arrayPos + "].createWaitLayer();",500);
      this.checkInt = setInterval("requests[" + this.arrayPos + "].checkSuccess();",1000);
    }
    else {
      this.inProgress = false;
      this.done = true;
    }
  }

  this.stateChange = function() {
    if ( this.getReadyState() == 4 ) {
      if ( this.loadingInt != false ) {
        clearInterval( this.loadingInt );
        this.loadingInt = false;
      }
      this.removeWaitLayer();
      if ( this.checkInt != false ) {
        clearInterval( this.checkInt );
        this.checkInt = false;
      }

      if ( this.getResponseCode() == 200 ) {
          this.obj.innerHTML = this.request.responseText;
          var scs = this.obj.getElementsByTagName('script');
          if ( scs ) {
            for ( i = 0; i < scs.length; i++ ) {
              eval( scs[i].innerHTML );
            }
          }
          if (typeof(XMLHttpRequest) == "undefined") setTimeout("reloadImages('" + this.element + "');", timeout);
          if ( typeof(ajaxPageAnchor) != "undefined" ) {
            elms = document.getElementsByName(ajaxPageAnchor);
            if ( elms && elms[0] ) {
              scrollTo(0, getYPos(elms[0]));
              ajaxPageAnchor = undefined;
            }
          }
      }
      else if ( this.getResponseCode() == -1 ) {
        this.cancel();
      }
      else {
        if ( this.getResponseCode() >= 400 && this.getResponseCode() < 500 ) window.location.replace( error400Page );
        
        else {location.replace( error500Page );}
      }
      document.getElementsByTagName('body')[0].style.cursor="auto";
      this.inProgress = false;
      this.done = true;
      requestPoller();
    }
    else if ( this.getReadyState() == -1 ) {
      this.cancel();
    }
    else {
      document.getElementsByTagName('body')[0].style.cursor="wait";
    }
  }

  this.calcArrayPos = function() {
    pos = -1;
    for ( i = 0; i < requests.length; i++ ) {
      if ( requests[i] == this ) pos = i;
    }
    this.arrayPos = pos;
  }

  this.getReadyState = function() {
    var ret = -1;
    try {
      ret = this.request.readyState;
    } catch ( e ) { ret = -1; }
    return ret;
  }

  this.getResponseCode = function() {
    var ret = -1;
    try {
      ret = this.request.status;
    } catch ( e ) { ret = -1; }
    return ret;
  }
}

ajaxLink = function(linkElm) {
  url   = linkElm.getAttribute('href');
  elmId = linkElm.getAttribute('elementId');
  if ( document.getElementById(elmId) ) {
    refreshElement(url,elmId);
  }
  else {
    alert("Error refreshing Box.");
  }
  return false;
}

/* replace html of element width html of url */
refreshElement = function( url, element ) {
  name = "request_" + new Date().getTime();
  showLoader = true;
  if ( refreshElement.arguments.length > 2 ) {
    showLoader = false;
  }
  var ret = new XMLRequest( url, element, name, showLoader, false, null );
  ret.request.onreadystatechange = function() { ret.stateChange(); };
  startAjaxRequest(ret);
  return ret; 
}

/* replace html of element width html response from a form post */
postFormAjax = function( form, element ) {
  name = "request_" + new Date().getTime();
  showLoader = true;
  if ( postFormAjax.arguments.length > 2 ) {
    showLoader = false;
  }

  var poststr = "";
  var url = "";

  if ( form) {
    url = form.action;
    for ( i = 0; i < form.elements.length; i++ ) {
      type = form.elements[i].type;

      if ( ( type != "radio"    && type != "checkbox" ) ||
           ( type == "radio"    && form.elements[i].checked == true ) ||
           ( type == "checkbox" && form.elements[i].checked == true ) ) {

        if ( poststr != "" ) poststr += "&";
        poststr += form.elements[i].name + "=" + encodeParamAjax(form.elements[i].value);
      }
    }
  }
  var ret = new XMLRequest( url, element, name, showLoader, true, poststr );
  ret.request.onreadystatechange = function() { ret.stateChange(); };
  startAjaxRequest(ret);
  //return ret; 
}

startAjaxRequest = function( request ) {
  requests.push( request  );
  //ret.execute();
  requestPoller();
}

requestPoller = function() {
  quit = false;
  for ( i = 0; i < requests.length && !quit; i++ ) {
    if ( requests[i].done == false && requests[i].inProgress == false ) {
      requests[i].execute();
      quit = true;
    }
    else if ( requests[i].done == false ) quit = true;
  }
}

