/**
 * @class Service
 * 
 * Not meant to be instantiated.
 * 
 * BCService.doAsyncGet()
 * Service.doAsyncPost()
 * 
 */
var BCService = {};

/*
 * doAsyncPost() and doAsyncGet() are the public functions that abstract all Ajax calls.
 * Currently using Prototype's Ajax.Request, may plug Yahoo's impl back in here.
 * 
 * Arguments:
 * 
 *  url: the service url up to and not including the ?
 *  parameters: object with request parameters as properties
 *  onSuccess: function reference for success callback. Will be called
 *    with the service's response object as the only argument.
 *  onFailure: function reference for failure callback. Will be called with no
 *    arguments.
 */
BCService.doAsyncGet = function (url, parameters, onSuccess, onFailure) {
  doAsyncRequest(url, "GET", parameters, onSuccess, onFailure);
}

BCService.doAsyncPost = function (url, parameters, onSuccess, onFailure) {
  doAsyncRequest(url, "POST", parameters, onSuccess, onFailure);
}

function doAsyncRequest (url, method, parameters, onSuccessCallback, onFailCallback) {
  // support for passing either a string, Prototype Hash object, or a native object
  if('string' != typeof(parameters)) parameters = $H(parameters).toObject();

  var onSuccess = function(xhr) {
    onSuccessCallback(xhr.responseText.evalJSON());
  };
  
  var onFail = function(xhr) {
    var failureStatus = xhr.responseText.evalJSON();
    if(failureStatus == 'LOGIN_REQUIRED') {
      window.onbeforeunload = undefined;
      window.location = '/login';
    } else {
      onFailCallback(failureStatus);
    }
  };

  /* Re-raise the exception so it isn't silently ignored. 
   * See: http://groups.google.com/group/prototype-scriptaculous/browse_thread/thread/e71c7a6bfb656380 */
  var onException = function(request, exception) { 
    (function() { throw exception; }).defer(); 
  }; 

  new Ajax.Request(
    url, {
      method: method,
      parameters: parameters,
      onSuccess: onSuccess,
      onFailure: onFail,
      onException: onException
  });
}
