// remote scripting library
// (c) copyright 2005 modernmethod, inc
// Changes (c) copyright 2006-2008 phloc systems OEG

var sajax_debug_mode = false;
// needs to be POST for large data (otherwise somewhere between 6000 - 7000
// chars is max!)
var sajax_request_type = "POST";
var sajax_target_id = "";
var sajax_failure_redirect = "";
var sajax_requests = new Array();
var sajax_function_name_param = "_name";

function _getCookie(sName) {
  var allCookies = document.cookie;
  var cookieArr = allCookies.split(";");
  for ( var i = 0; i < cookieArr.length; i++) {
    var cookie = cookieArr[i].split("=");
    // perform a trim on the name - may have leading spaces!
    var sCookieName = cookie[0].replace(/^\s*(\S+)\s*$/, '$1');
    if (sCookieName == sName)
      return unescape(cookie[1]);
  }
  alert('cookie not found');
  return null;
}

function _findSajaxRemoteUriInCookie() {
  if (typeof (sajax_remote_uri) == 'undefined') {
    // get the base path from the cookie
    var sCookie = _getCookie('pdaf_ajax');
    if (sCookie)
      sajax_remote_uri = sCookie;
    else
      alert('Failed to connect to the surrounding application - no AJAX call possible');
  }
}

function sajax_debug(text) {
  if (sajax_debug_mode && text)
    alert(text);
}

function sajax_init_object() {
  sajax_debug("sajax_init_object() called..")

  var A;

  var msxmlhttp = new Array('Msxml2.XMLHTTP.5.0', 'Msxml2.XMLHTTP.4.0',
      'Msxml2.XMLHTTP.3.0', 'Msxml2.XMLHTTP', 'Microsoft.XMLHTTP');
  for ( var i = 0; i < msxmlhttp.length; i++) {
    try {
      A = new ActiveXObject(msxmlhttp[i]);
    } catch (e) {
      A = null;
    }
  }

  if (!A && typeof XMLHttpRequest != "undefined")
    A = new XMLHttpRequest();
  if (!A)
    sajax_debug("Could not create connection object.");
  return A;
}

function sajax_cancel() {
  for ( var i = 0; i < sajax_requests.length; i++)
    sajax_requests[i].abort();
}

function sajax_do_call(sDesiredURI, sFuncName, argCallback, args) {
  var i, x, n;
  var uri;
  var post_data;
  var target_id;

  sajax_debug("in sajax_do_call()\nDesired URO: " + sDesiredURI
      + "\nRequest type: " + sajax_request_type + "\nTarget ID: "
      + sajax_target_id);
  target_id = sajax_target_id;

  uri = sDesiredURI ? sDesiredURI : sajax_remote_uri;
  if (typeof uri == "undefined")
    alert("SAJAX Remote URI is undefined");

  if (sajax_request_type == "GET") {
    if (uri.indexOf("?") == -1)
      uri += "?";
    else
      uri += "&";
    
    // NOTE: always use encodeURIComponent instead of escape
    // because it converts elements to UTF-8!
    uri += sajax_function_name_param + "=" + encodeURIComponent(sFuncName);
    uri += "&rst=" + encodeURIComponent(sajax_target_id);
    uri += "&rsrnd=" + new Date().getTime();

    if (args)
      for (i = 0; i < args.length; i++)
        uri += "&rsargs[]=" + encodeURIComponent(args[i]);

    post_data = null;
  } else if (sajax_request_type == "POST") {
    post_data = sajax_function_name_param + "=" + encodeURIComponent(sFuncName);
    post_data += "&rst=" + encodeURIComponent(sajax_target_id);
    post_data += "&rsrnd=" + new Date().getTime();

    if (args)
      for (i = 0; i < args.length; i++)
        post_data = post_data + "&rsargs[]=" + encodeURIComponent(args[i]);
  } else {
    alert("Illegal request type: " + sajax_request_type);
  }
  sajax_debug("uri = " + uri + "\npost_data = " + post_data);

  x = sajax_init_object();
  if (x == null) {
    if (sajax_failure_redirect != "") {
      location.href = sajax_failure_redirect;
      return false;
    } else {
      sajax_debug("NULL sajax object for user agent:\n" + navigator.userAgent);
      return false;
    }
  } else {
    x.open(sajax_request_type, uri, true);
    // window.open(uri);

    sajax_requests[sajax_requests.length] = x;

    if (sajax_request_type == "POST") {
      x.setRequestHeader("Method", "POST " + uri + " HTTP/1.1");
      x.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    }

    x.onreadystatechange = function() {
      if (x.readyState != 4)
        return;

      sajax_debug("received " + x.responseText);

      var status;
      var data;
      var txt = x.responseText.replace(/^\s*|\s*$/g, "");
      status = txt.charAt(0);
      data = txt.substring(2);

      if (status == "") {
        // let's just assume this is a pre-response bailout and let it slide for
        // now
      } else if (status == "-")
        alert("Error: " + data);
      else {
        if (target_id != "")
          document.getElementById(target_id).innerHTML = eval(data);
        else {
          try {
            var callback;
            var extra_data = false;
            if (typeof argCallback == "object") {
              callback = argCallback.callback;
              extra_data = argCallback.extra_data;
            } else {
              callback = argCallback;
            }
            var res = null;
            try {
              res = eval(data);
            } catch (e) {
              // was: sajax_debug
              alert("Caught eval error " + e + "!\nTo eval: " + data);
            }
            callback(res, extra_data);
          } catch (e) {
            // was: sajax_debug
            alert("Caught error in callback: " + e + "!");
          }
        }
      }
    }
  }

  sajax_debug(sFuncName + " uri = " + uri + "\n/post = " + post_data);
  x.send(post_data);
  sajax_debug(sFuncName + " waiting..");
  delete x;
  return true;
}
