/*
  PFrameworkCS API
  
  Copyright (C) 2005 by Jernej Kos <kostko@jweb-network.net>
  Copyright (C) 2005 by Unimatrix-One (www.unimatrix-one.org)
  
  This javascript is part of the PFramework CMS system. Any unauthorised
  use outside of this system is strictly prohibited.
*/

var s_rpcInstance;

var PRPC = function(uri)
{
  s_rpcInstance = this;
  this.requestUri = uri;
  
  // Initialise our HTTP transport
  this.InitTransport();
}

PRPC.prototype.InitTransport = function()
{
  var transport = false;
  
  if (window.XMLHttpRequest) {
    transport = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    try {
      transport = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (E) {
      try {
        transport = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (E) {
        transport = false;
      }
    }
  }
  
  this.transport = transport;
}

PRPC.prototype.EncodePostParams = function(params)
{
  var jsonEncode = toJSON(params);
  var data;
  
  data = 'rpcParams=' + escape(jsonEncode);
  
  return data;
}

PRPC.prototype.CallMethod = function(method, params, callback, p)
{
  var url = this.requestUri + 'RPC:' + method;
  var data = this.EncodePostParams(params);
  
  var t = this.transport;
  
  t.open("POST", url, true);
  t.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  
  t.onreadystatechange = function() {
    if (t.readyState == 4) {
      if (t.status != 200) {
        return;
      }

      // Data fetch is done :)
      var resp = eval('(' + t.responseText + ')');
      
      // Call the callback
      callback(resp, p);
    }
  }
  
  t.send(data);
}


