
/* Create a new XMLHTTPRequest object */
function create_http_request()
{
  /*
  var req = null;
  try {
    req = new ActiveXObject("Msxml2.XMLHTTP");
  } catch (e1) {
    try {
      req = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (e2) {
      req = new XMLHttpRequest();
    }
  }
  return req;
  */
  return window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP");
}

/* Show calendar */
function show_calendar_nx(form_id)
{
  //var el = document.getElementById(form_id);
  //if (! el) return;
  var value = eval("document." + form_id + ".value");
  var win = window.open('calendar.pl?form_id=' + form_id + '&date=' + escape_url(value), 'calendar',
                        'width=300,height=200,status=no,titlebar=no');
}

show_calendar = show_calendar_cp;
// show_calendar = show_calendar_nx;

/* Escape an URL string */
function escape_url(str)
{
  if (str == null)
    return null;
  var i;
  var n = str.length;
  var out = '';
  for (i = 0; i < n; i++)
    if (str.charAt(i).match(/[^0-9A-Za-z_]/)) {
      var x = '00' + str.charCodeAt(i).toString(16);
      out += '%' + x.substr(x.length - 2, 2);
    } else
      out += str.charAt(i);
  return out;
}

/* Build a POST string from an object containing the key/value pairs
 * to be sent. */
function build_post(a)
{
  var k, str = '';
  for (k in a) {
    if (str.length > 0) str += '&';
    str += escape_url(k) + '=' + escape_url(a[k]);
  }
  return str;
}

/* Retrieve the attributes from a DOM Element in an object. */
function get_element_attrs(el)
{
  var v = {};
  for (var i = 0; i < el.attributes.length; i++) {
    v[el.attributes[i].nodeName] = el.attributes[i].nodeValue;
  }
  return v;
}

function get_choice_list_items(root_el)
{
  var items = [];
  var m = root_el.childNodes.length;
  for (var j = 0; j < m; j++) {
    var item = root_el.childNodes[j];
    if (item.nodeType != 1 || item.tagName.toLowerCase() != 'item')
      continue;
    attrs = get_element_attrs(item);
    items[items.length] = attrs['value'];
  }
  return items;
}

/*
 * Perform a XMLHttpRequest and expect it to return a XML containing
 * information about the changed fields.
 */
function nx_perform_request(url, vars, set_field_func,
                            set_choicelist_func, err_func)
{
  var req = create_http_request();

  log_str('*** request (sync): ' + url);

  req.open('POST', url + '?r=' + Math.random(), false);
  req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  var timeout = setTimeout(function() { log_str('aborted'); req.abort(); }, 5000);
  req.send(build_post(vars));
  clearTimeout(timeout);

  if (! req.responseXML) {
    err_func(vars, 'Error reading XML (no responseXML)');
    return;
  }

  // get the root element
  var resp = req.responseXML.documentElement;
  if (resp == null) {
    err_func(vars, 'Error reading XML (can\'t find XML root)');
    //alert(req.responseText);
    return;
  }
  if (resp.tagName.toLowerCase() == 'error') {
    var error = '';
    var n = resp.childNodes.length;
    for (var i = 0; i < n; i++) {
      if (resp.childNodes[0].nodeType == 3)
        error += '"' + resp.childNodes[0].nodeValue + '"';
    }
    err_func(vars, 'remote error: ' + error);
    return;
  }
  
  // sweep all children tags
  var n = resp.childNodes.length;
  for (var i = 0; i < n; i++) {
    var tag = resp.childNodes[i];
    if (tag.nodeType != 1) continue;

    switch (tag.tagName.toLowerCase()) {
    case 'field':
      // call the callback function with the attributes
      var attrs = get_element_attrs(tag);
      if (set_field_func != null)
        set_field_func(vars, attrs['name'], attrs['value'],
                       attrs['requiredness']);
      break;

    case 'choicelist':
      // call the callback function with the list of values
      var attrs = get_element_attrs(tag);
      var choice_name = attrs['name'];
      var must_reload = (attrs['items'] && attrs['items'] == 'false');
      if (set_choicelist_func != null)
        set_choicelist_func(vars, choice_name, get_choice_list_items(tag),
                            must_reload);
      break;
    }
  }
}

