// +------------------------------------------------------------------------+
// | goCalendar                                                             |
// +------------------------------------------------------------------------+
// | Copyright (c) 2005 Starfield Technologies                              |
// | Authors       Vincent Fiduccia, David Koopman                          |
// | Email         support@starfieldtech.com                                |
// | Web           http://www.starfieldtech.com                             |
// +------------------------------------------------------------------------+
// | This source file is subject to version 1.0 of the Starfield            |
// | Technologies, Inc. License, that is available at                       |
// | http://www.starfieldtech.com/changme/to/license.txt                    |
// | that is available at http://www.php.net/license/3_0.txt.               |
// +------------------------------------------------------------------------+
//

var last_callid=0;
var rpcIframes = new Array();
var rpcCallbacks = new Array();
var rpcParams = new Array();
//var rpcSyncWait = new Array();
var aImgForRpcSignal = new Array();

// This comes from layermagic..
function IframeGetDoc(iframe)
{
  if (iframe.contentDocument) // For NS6
    return iframe.contentDocument;

  if (iframe.contentWindow) // For IE5.5 and IE6
    return iframe.contentWindow.document;

  if (iframe.document) // For IE5
    return iframe.document;

  return false;
}

function arrayToQueryString(params)
{
  var qs = '';
  var i;

  for ( param in params )
  {
    if ( typeof params[param] == 'object' || typeof params[param] == 'array' )
    {
      for ( i = 0 ; i < params[param].length ; i++ )
      {
        qs += ((qs=='')?'':'&') + param +'[]=' + escape(params[param][i]);
      }
    }
    else
      qs += ((qs=='')?'':'&') + param +'='+escape(params[param]);
  }

  return qs;
}

function buildQueryString(start,theForm)
{
  var qs = '';

  if ( start )
    qs = '?' + start;
  
  for (e=0;e<theForm.elements.length;e++) 
  {
    if (theForm.elements[e].name!='') 
    {
      qs+=(qs=='')?'?':'&';
      qs+=theForm.elements[e].name+'='+escape(theForm.elements[e].value);
    }
  }
  return qs;
}

function rpcSignal(URL)
{
  // Have to give a randomized URL or IE will cache the image and never make the request
  var randNum1 = Math.floor(Math.random()*10000000);
  var modURL = URL + ( URL.indexOf("?") >= 0 ? "&" : "?" ) + "rand=" + randNum1 + "&callid=" + last_callid++;
  if ( modURL.length <= 1900 )
  {
    aImgForRpcSignal[aImgForRpcSignal.length] = new Image();
    aImgForRpcSignal[aImgForRpcSignal.length-1].src = modURL;
  }
  else
  {
    var params;
    if ( URL.indexOf("?") == -1 )
    {
      params = new Array();
    }
    else
    {
      params = queryStringToAssoc(URL.substring(URL.indexOf("?")+1, URL.length));     
      URL = URL.substring(0, URL.indexOf("?"));
    }
    rpcAsyncPost(URL, params);
  }
}

/* Synchronous doesn't work yet... need a way to sit and wait without locking the browser.
function rpcSync(URL)
{
  var callid = rpcAsync(URL,rpcSyncCallback);
alert("rpcSync("+URL+") called: " + callid);
  rpcSyncWait[callid] = 1;

  while ( ! getResponse(callid) )
  {
    // Spin our wheels waiting for a response
  }

  return getResponse(callid); 
}

function rpcSyncCallback(callid)
{
  alert('sync callback');
  rpcSyncWait[callid] = 0;
}
*/

function makeIframe(callid)
{
  var frameName = 'rpcFrame_'+callid;
  if (!rpcIframes[callid] && document.createElement)
  {
    // create the IFrame and assign a reference to the
    // object to our global variable rpcIframes[callid].
    try
    {
      var tempIFrame=document.createElement('iframe');
      tempIFrame.setAttribute('id',frameName);
      tempIFrame.style.border='0px';
      tempIFrame.style.width='0px';
      tempIFrame.style.height='0px';
      tempIFrame.src = 'blank.html';
      rpcIframes[callid] = document.body.appendChild(tempIFrame);
      if (document.frames)
      {
        // For IE5 Mac
        rpcIframes[callid] = document.frames[frameName];
      }
    } catch(exception) {
      // For IE5 PC, no dynamic creation
      iframeHTML='<iframe src="blank.html" id="'+frameName+'" style="';
      iframeHTML+='border:0px;';
      iframeHTML+='width:0px;';
      iframeHTML+='height:0px;';
      iframeHTML+='"><\/iframe>';
      document.body.innerHTML+=iframeHTML;
      rpcIframes[callid] = new Object();
      rpcIframes[callid].document = new Object();
      rpcIframes[callid].document.location = new Object();
      rpcIframes[callid].document.location.iframe = document.getElementById(frameName);
      rpcIframes[callid].document.location.replace = function(location) {
        this.iframe.src = location;
      }
    }
  }

  return frameName;
}

function rpcAsync(URL,callback,force_callid)
{
  var callid = ( force_callid != null ? force_callid : last_callid++ );

  if ( force_callid == null)
    URL += ( URL.indexOf("?") >= 0 ? "&" : "?" ) + "rand=" + Math.floor(Math.random()*100000) + "&callid=" + callid;

  if (!document.createElement) {return true};
  makeIframe(callid);
  if ( callback != null )
    rpcCallbacks[callid] = callback;
  if (navigator.userAgent.indexOf('Gecko') !=-1 && !rpcIframes[callid].contentDocument)
  {
    // we have to give NS6 a fraction of a second to recognize the new IFrame
    setTimeout('rpcAsync("'+URL+'",null,'+callid+')',10);
    return callid;
  }

  var IframeDoc = IframeGetDoc(rpcIframes[callid]);

  IframeDoc.location.replace(URL);
  return callid;
}

function rpcAsyncPost(URL,params,callback,force_callid,retry)
{
  var callid = ( force_callid != null ? force_callid : last_callid++ );

  if ( force_callid == null)
    URL += ( URL.indexOf("?") >= 0 ? "&" : "?" ) + "rand=" + Math.floor(Math.random()*100000);

  if ( params == "load" )
  {
    if ( rpcParams[callid] )
      params = rpcParams[callid];
    else
      params = new Array();
  }

  if (!document.createElement) {return true};

  var frameName = makeIframe(callid);

  if ( callback != null )
    rpcCallbacks[callid] = callback;

  var IframeDoc = IframeGetDoc(rpcIframes[callid]);

  if ( ! retry)
  {
    rpcParams[callid] = params;
    // we have to give NS6 a fraction of a second to recognize the new IFrame
    setTimeout('rpcAsyncPost("'+URL+'","load",null,'+callid+',true)',10);
    return callid;
  }

  if ( ! params['callid'] )
    params['callid'] = ""+callid;

  IframePost(frameName,URL,params);

  return callid;
}

function rpcAsyncCallback(callid)
{
//  alert('async callback: ' + callid);

  if ( rpcCallbacks[callid] && rpcCallbacks[callid] != null )
  {
    var response = getResponse(callid);

/*    if ( rpcCallbacks[callid] == rpcSyncCallback )
    {
      rpcSyncCallback(callid);
    }
    else*/
    if ( typeof rpcCallbacks[callid] == 'function' )
      rpcCallbacks[callid](response);
    else
      eval(rpcCallbacks[callid]);
  }
}

function getResponse(callid)
{
  var doc = IframeGetDoc(rpcIframes[callid]);
  if ( doc && doc.getElementById("rpcResponse") )
  {
    return doc.getElementById("rpcResponse").innerHTML;
  }
  else
  {
    return false;
  }
}

// This doesn't really belong here, but it's too short to put in it's own file...
function rememberSetting(name,value)
{
    rpcSignal('/rpc_rememberSetting.php?name='+name+'&value='+escape(value));
}
