/**
 * @class DWRResultProcessor
 * 
 * The DWRResultProcessor connects the result beans with functions. It processes the returned DWRResult object.
 */
var DWRResultProcessor = (function()
{
  /** A map that connects the result bean name with a function. */
  var viewUpdateBeanLookup = {};

  /** The constructor is empty because all functions are static. */
  function constructorFn()
  {
  }

  /**
   * Connects a bean name with a function.
   *
   * @param {String} beanName a bean name
   * @param {function} updateFunction the function for the given bean name
   */
  constructorFn.registerResultFunction = function(beanName, updateFunction)
  {
    viewUpdateBeanLookup[beanName] = updateFunction;
  }

  /**
   * Processes a DWR result. It checks whether the request was successful and then executes all functions for the
   * returned beans.
   *
   * @param {ViewUpdateBean} dwrResult a DWR result
   */
  constructorFn.processDWRResult = function(dwrResult)
  {
    if(dwrResult.success)
    {
      var updateBeans = dwrResult.updateBeans;
      for(var i = 0; i < updateBeans.length; i++)
      {
        var updateBean = updateBeans[i];
        var beanName = updateBean.beanName;
        var updateFunction = viewUpdateBeanLookup[beanName];
        if(updateFunction == null)
        {
          alert("Missing update function for bean name \'" + beanName + "\'");
        }
        else
        {
          updateFunction(updateBean);
        }
      }
    }
    else
    {
      var message = dwrResult.message;
      if(message == null)
      {
        message = 'AJAX operation failed';
      }
      alert(message);
    }
  }

  /* return the constructor. */
  return constructorFn;
})(); //simultaneously define and call (one-off)!

