/*
    Document   : serviceproxy.js
    Created on : 07-jan-2010
    Author     : Bjorn
    Description:
        Class that automates the calling of server side classes
        through the servicejson.php.
*/

var ServiceProxy = {};

ServiceProxy.Call = function(serviceName, methodName, parameters, callBack, validationExceptionCallback)
{
  var obj = {ServiceName: serviceName, MethodName: methodName, Arguments: parameters};

  jQuery.ajax
  ({
   type: "POST",
   url: HTTPREQ_DISPATCHER_FILENAME,
   cache: false,
   processData: false,
   data: JSON.stringify(obj),
   error: ServiceProxy_Error,
   success: function(data, textstatus){ ServiceProxy_CallResult(data, textstatus, callBack, validationExceptionCallback); }
  })
  
}

/*
 * Triggered when the XMLHttpRequest reports an error (for instance if the server returns a 500 internal exception)
 */
ServiceProxy_Error = function(XMLHttpRequest, textStatus, errorThrown)
{
  $("#popupcontent").dialog('close');
  $("#popupcontent").attr("title", "Er is een onverwachte fout opgetreden");
  $("#popupcontent").html('<p><span class="ui-icon-error ui-icon-alert" style="float:left; margin:0 7px 50px 0;"></span>' + textStatus + ' - ' + errorThrown + '</p>');
  $("#popupcontent").dialog({
			bgiframe: true,
			modal: true,
      draggable: false,
      resizable: false,
			buttons: {
				Ok: function() {
					$(this).dialog('close');
				}
			}
		});

}

/*
 * Triggered when the result is not "ok" (succesful call to service class, but error thrown by PHP code)
 */
ServiceProxy_PHPError = function(errorText)
{
  $("#popupcontent").dialog('close');
  $("#popupcontent").attr("title", "Er is iets misgegaan");
  $("#popupcontent").html('<p><span class="ui-icon-error ui-icon-alert" style="float:left; margin:0 7px 50px 0;"></span>' + errorText + '</p>');
  $("#popupcontent").dialog({
			bgiframe: true,
			modal: true,
      draggable: false,
      resizable: false,
			buttons: {
				Ok: function() {
					$(this).dialog('close');
				}
			}
		});
}

/*
 * Triggered when XMLHttpRequest reports a successful call.
 */
ServiceProxy_CallResult = function(data, textStatus, callBack, validationExceptionCallback)
{
  resultObject = JSON.parse(data);
  if(resultObject.result == "ok")
  {
    if(callBack != null)
    {
      callBack(resultObject.retval);
    }
  }
  else if(resultObject.result == "ValidationException")
  {
    if(validationExceptionCallback != null)
    {
      validationExceptionCallback(resultObject.retval);
    }
    else
    {
      ServiceProxy_PHPError(resultObject.retval.ErrorMessage);
    }
  }
  else
  {
    ServiceProxy_PHPError(resultObject.retval);
  }
}