/*
  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.
*/

// Exceptions
var PException = function PException(code, message)
{
  this.code = code;
  this.message = message;
}

var s_rpcInstance;

var PRPC = function(uri)
{
  s_rpcInstance = this;
  this.requestUri = uri;
}

PRPC.prototype.SetAuthKey = function(key)
{
  this.authKey = key;
}

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;
      }
    }
  }

  return transport;
}

PRPC.prototype.EncodePostParams = function(params)
{
  var jsonEncode = params.toJSON();
  var data;
  
  data  = 'rpcAuthKey=' + this.authKey;
  data += '&rpcParams=' + escape(jsonEncode).replace(/\+/g, '%2B');
  
  return data;
}

PRPC.prototype.CallMethod = function(method, params, callback, p)
{
  var url = this.requestUri + 'RPC:' + method;
  if (window.location.protocol == 'https:')
    url = url.replace('http', 'https');
  var data = this.EncodePostParams(params);

  // Initialise our HTTP transport
  var t = this.InitTransport();
  
  t.open("POST", url, true);
  t.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  
  t.onreadystatechange = function() {
    if (t.readyState == 4) {
      var resp;
      var received_tokens;
      var isError = (t.getResponseHeader("X-PF-Error") == "true");
      
      try {
        if (t.status != 200)
          throw new Error();
        
        resp = eval('(' + t.responseText + ')');
        received_tokens = resp.received_tokens;
        resp = resp.output;

        if (isError)
          resp = new PException(resp['pf:code'], resp['pf:exception']);
      } catch (E) {
        resp = new PException(0, "Internal server error has ocurred.<br /><div style='height: 300px; overflow:auto;'>Debuging:" + t.responseText + "<br />Sent: " + data + "</div>");
      }
      
      // Call the callback
      callback(resp, p);
      
      // Show tokens
      try {
        podnapisiShowTokens(received_tokens);
      } catch (E) {
      }
    }
  }
  
  t.send(data);
}


