// This file contains some simple utilities 
// based on prototype.js which I need on the site.

var DEFAULT_URL = "/cgi-bin/website.cgi";

function webRequest(parameters) {
  var url = DEFAULT_URL;
  var cache_path = null;
  if (parameters.url) {
    url = parameters.url;
    delete parameters.url;
  }
  if (parameters.cache_path) {
    cache_path = parameters.cache_path;
    delete parameters.cache_path;
  }  
  // Default is synchronous.
  if (parameters.asynchronous === undefined) {
    parameters.asynchronous = false;
  }
  if (cache_path) {
    var onSuccess = parameters.onSuccess;
    var p = parameters;
    new Ajax.Request("/_cache/" + cache_path, {
      asynchronous: false,
      method: "get",
      onSuccess: function (transport) {
	if (onSuccess) {
	  onSuccess(transport);
	}
      },
      onFailure: function (transport) {
	if (transport.status == 404) {
	  p.parameters.cache_path = cache_path;
	  new Ajax.Request(url, p);
	}
      }
    });
  } else {
    new Ajax.Request(url, parameters);
  }
}

// Takes parameters and an optional argument which
// is the ID of the node to insert the HTML.
// Otherwise, it's written to the current document.

function insertResult(parameters) {
  var insertNodeFn = function (transport) {
    document.write(transport.responseText);
  }
  if (arguments.length > 1) {
    var nodeName = arguments[1];
    insertNodeFn = function (transport) {
      $(nodeName).innerHTML = transport.responseText;
    }
  }
  parameters.onSuccess = insertNodeFn;
  webRequest(parameters);
}

function retrieveJSON(parameters) {
  var result = null;
  parameters.asynchronous = false;
  parameters.onSuccess = function (transport) {
    result = transport.responseText.evalJSON(true);
  }
  webRequest(parameters);
  return result;
}
