//
//  jsrsClient.js - javascript remote scripting client include
//
//  Author:  Brent Ashley [jsrs@megahuge.com]
//
//  make asynchronous remote calls to server without client page refresh
//
//  see license.txt for copyright and license information
/*
see history.txt for full history
2.0  26 Jul 2001 - added POST capability for IE/MOZ
2.2  10 Aug 2003 - added Opera support
2.3(beta)  10 Oct 2003 - added Konqueror support - **needs more testing**
*/
// callback pool needs global scope
var jsrsContextPoolSize = 0;
var jsrsContextMaxPool = 20;
var jsrsContextPool = new Array();
var jsrsBrowser = jsrsBrowserSniff();
var jsrsPOST = true;
var jsrsWinDebug = true;
var containerName;
var Mensaje_Loading = Mensaje_Loading ? Mensaje_Loading : "Cargando...";
var dirLibsPHP = dirLibsPHP ? dirLibsPHP : "./";
var axHTMLCharSet = axHTMLCharSet ? axHTMLCharSet : "ISO-8859-1";

// constructor for context object
function jsrsContextObj( contextID )
{
  // properties
  this.id = contextID;
  this.busy = true;
  this.callback = null;
  this.container = contextCreateContainer( contextID );
  // methods
  this.GET = contextGET;
  this.POST = contextPOST;
  this.POSTpage = contextPOSTpage;
  this.POSTupload = contextPOSTupload;
  this.getPayload = contextGetPayload;
  this.setVisibility = contextSetVisibility;
  if(!this.container) Anuncio("Fallo la creacion del Contenedor");
}
//  method functions are not privately scoped
//  because Netscape's debugger chokes on private functions
function contextCreateContainer( containerName ){
  // creates hidden container to receive server data
	var container;
	switch( jsrsBrowser )
	{
	   case 'NS':
			container = new Layer(100);
			container.name = containerName;
			container.id = containerName;
			container.style.position = 'absolute';
			if (jsrsWinDebug)
			{
	      	container.clip.width = 100;
	      	container.clip.height = 100;
			}
			else
			{
		      container.visibility = 'hidden';
	      	container.clip.width = 1;
	      	container.clip.height = 1;
	      }
		break;
		case 'IE':
	      document.body.insertAdjacentHTML( "afterBegin", '<span id="SPAN' + containerName + '" style="position:absolute; z-index:100; background-color: white;"></span>' );
	      var span = document.all( "SPAN" + containerName );
	      //var html = '<iframe name="' + containerName + '" id="' + containerName + '" src="/' + dirLibsPHP + '/blank.php" width="200" height="200"></iframe>';
	      //var html = '<iframe name="' + containerName + '" id="' + containerName + '" src="blank.php" width="200" height="200"></iframe>';
	      //var html = '<iframe name="' + containerName + '" id="' + containerName + '" src="blank.php" width="1" height="1"></iframe>';
			if (jsrsWinDebug)
		      var html = '<iframe name="' + containerName + '" id="' + containerName + '" src="blank.php" width="200" height="200"></iframe>';
			else
		      var html = '<iframe name="' + containerName + '" id="' + containerName + '" src="blank.php" width="1" height="1"></iframe>';
	      span.innerHTML = html;
	     	span.style.display = 'none';
	      container = window.frames[ containerName ];
		  	if(!container) {container = oBusca(containerName);}
	      break;
		case 'MOZ':
	      var span = document.createElement('SPAN');
	      span.id = "SPAN" + containerName;
	      //span.style = "background-color:white";
			span.style.position = "absolute";
			//span.style.zIndex = "100";
			span.style.zIndex = "-1";
	      document.body.appendChild( span );
	      var iframe = document.createElement('IFRAME');
	      iframe.name = containerName;
	      iframe.id = containerName;
			if (jsrsWinDebug)
	      	iframe.style.visibility = "visible";
			else
	      	iframe.style.visibility = "hidden";
	      iframe.height = 100;
	      iframe.width = 100;
	      span.appendChild( iframe );
	      container = iframe;
		break;
		case 'OPR':
	      var span = document.createElement('SPAN');
	      span.id = "SPAN" + containerName;
			span.style = "position:absolute; z-index:100";
	      document.body.appendChild( span );
	      var iframe = document.createElement('IFRAME');
	      iframe.name = containerName;
	      iframe.id = containerName;
	      span.appendChild( iframe );
	      container = iframe;
		break;
		case 'KONQ':
	      var span = document.createElement('SPAN');
	      span.id = "SPAN" + containerName;
			span.style.position ="absolute";
	      document.body.appendChild( span );
	      var iframe = document.createElement('IFRAME');
	      iframe.name = containerName;
	      iframe.id = containerName;
	      span.appendChild( iframe );
	      container = iframe;
	      // Needs to be hidden for Konqueror, otherwise it'll appear on the page
	      span.style.display = none;
	      iframe.style.display = none;
	      iframe.style.visibility = hidden;
	      iframe.height = 0;
	      iframe.width = 0;
		break;
	}
	return container;
}
function contextPOST( rsPage, func, parms ){
  var d = new Date();
  var unique = d.getTime() + '' + Math.floor(1000 * Math.random());
  var doc = (jsrsBrowser == "IE" ) ? this.container.document : this.container.contentDocument;
  doc.open();

  var axHTMLDoc =  "<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN' 'http://www.w3.org/TR/html4/loose.dtd'>"+
    					"<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset="+axHTMLCharSet+"\"><title></title></head><body>";

  doc.write(axHTMLDoc);

  doc.write('<form name="jsrsForm" method="post" target="" charset="'+axHTMLCharSet+'"');
	if(rsPage.match("\\?") == "?")
  	doc.write(' action="' + rsPage + '&U=' + unique + '">');
	else
  	doc.write(' action="' + rsPage + '?U=' + unique + '">');
	doc.write('<input type="hidden" name="C" value="' + this.id + '">');
  	// func and parms are optional
	if (func != null){
	doc.write('<input type="hidden" name="F" value="' + func + '">');
    if (parms != null){
      if (typeof(parms) == "string"){
        // single parameter
        doc.write( '<input type="hidden" name="P0" '
                 + 'value="[' + jsrsEscapeQQ(parms) + ']">');
      }
		else
		{
        // assume parms is array of strings
        /*
				// 2005-08-22
				// Comentado por xButil para solucionar el problema de los
				// campos textarea con chr(10), chr(13)
				for( var i=0; i < parms.length; i++ )
		  	{
			  	doc.write( '<input type="text" name="P' + i + '" '
          	+ 'value="[' + jsrsEscapeQQ(parms[i]) + ']">');
					// added by xButil
					// alert(parms[i]+' *** '+jsrsEscapeQQ(parms[i]));
 		 		}*/
			for( var i=0; i < parms.length; i++ )
		  	{
			  	doc.write( '<textarea name="P' + i + '" >[' + jsrsEscapeQQ(parms[i]) + ']</textarea>');
 		 	}
      } // parm type
    } // parms
  } // func
  doc.write("</form></body></html>");
  doc.close();
  doc.forms['jsrsForm'].submit();
}
function contextGET( rsPage, func, parms ){
  // build URL to call
  //var URL = "https://"+rsPage;
  var URL = rsPage;
  // always send context
  URL += "?C=" + this.id;
  // func and parms are optional
  if (func != null){
    URL += "&F=" + escape(func);
    if (parms != null){
      if (typeof(parms) == "string"){
        // single parameter
        URL += "&P0=[" + escape(parms+'') + "]";
      } else {
        // assume parms is array of strings
        for( var i=0; i < parms.length; i++ ){
          URL += "&P" + i + "=[" + escape(parms[i]+'') + "]";
        }
      } // parm type
    } // parms
  } // func
  // unique string to defeat cache
  var d = new Date();
  URL += "&U=" + d.getTime();
  // make the call
  switch( jsrsBrowser ) {
    case 'NS':
      this.container.src = URL;
      break;
    case 'IE':
      this.container.document.location.replace(URL);
      break;
    case 'MOZ':
      this.container.src = '';
      this.container.src = URL;
      break;
    case 'OPR':
      this.container.src = '';
      this.container.src = URL;
      break;
    case 'KONQ':
      this.container.src = '';
      this.container.src = URL;
      break;
  }
}
function contextPOSTpage( rsPage, form ){
  var d = new Date();
  var unique = d.getTime() + '' + Math.floor(1000 * Math.random());
  var doc = (jsrsBrowser == "IE" ) ? this.container.document : this.container.contentDocument;
  doc.open();
  doc.write('<html><body>');
  doc.write('<form name="jsrsForm" method="post" target="" ');
	if(rsPage.match("\\?") == "?")
  	doc.write(' action="' + rsPage + '&U=' + unique + '">');
	else
  	doc.write(' action="' + rsPage + '?U=' + unique + '">');

  doc.write('<input type="hidden" name="C" value="' + this.id + '">');
  if(form != "")
  {
	  tmpF = (oBusca(form))? oBusca(form).elements : new Array();
	  for(nIN=0; nIN<tmpF.length; nIN++)
	  {
	    doc.write( '<' + tmpF.item(nIN).nodeName + ' type="' + tmpF.item(nIN).type + '" name="' + tmpF.item(nIN).name + '" value="' + tmpF.item(nIN).value + '" />' );
	  }
	}

  doc.write("</form></body></html>");
  //alert('contextPOSTpage: (222)'+doc.innerHTML);
  doc.close();
  doc.forms['jsrsForm'].submit();
}
function contextPOSTupload( rsPage, _input ){
  var d = new Date();
  var unique = d.getTime() + '' + Math.floor(1000 * Math.random());
  var doc = (jsrsBrowser == "IE" ) ? this.container.document : this.container.contentDocument;
  doc.open();
  doc.write('<html><body>');
  doc.write('<form name="jsrsForm" method="post" target="" ');
	if(rsPage.match("\\?") == "?")
  	doc.write(' action="' + rsPage + '&U=' + unique + '">');
	else
  	doc.write(' action="' + rsPage + '?U=' + unique + '">');

  doc.write('<input type="hidden" name="C" value="' + this.id + '">');
  doc.write('<input type="hidden" name="F" value="upload_file">');
  doc.write('<input name="P0" value="' + _input + '">');
  doc.write('<input name="P1" value="' + _input + '">');
  if(_input != "")
  {
	  tmpF = (oBusca(_input))? oBusca(_input): null;
// 	  alert(tmpF.name + "\n" + tmpF.value);
    doc.write('<input name="file" type="file" value="' + tmpF.value + '">');
// 	  for(nIN=0; nIN<tmpF.length; nIN++)
// 	  {
// 	    doc.write( '<' + tmpF.item(nIN).nodeName + ' type="' + tmpF.item(nIN).type + '" name="' + tmpF.item(nIN).name + '" value="' + tmpF.item(nIN).value + '" />' );
// 	  }
	}

  doc.write("</form></body></html>");
  //alert('contextPOSTpage: (222)'+doc.innerHTML);
  doc.close();
//   doc.forms['jsrsForm'].submit();
}
function contextGetPayload(){
  switch( jsrsBrowser ) {
    case 'NS':
      return this.container.document.forms['jsrs_Form'].elements['jsrs_Payload'].value;
    case 'IE':
      return this.container.document.forms['jsrs_Form']['jsrs_Payload'].value;
    case 'MOZ':
      return window.frames[this.container.name].document.forms['jsrs_Form']['jsrs_Payload'].value;
    case 'OPR':
      var textElement = window.frames[this.container.name].document.getElementById("jsrs_Payload");
    case 'KONQ':
      var textElement = window.frames[this.container.name].document.getElementById("jsrs_Payload");
      return textElement.value;
  }
return "";
}
function GetDoc(nom)
{
  var x = null;
  var y = null;
  var z = null;

  switch( jsrsBrowser ) {
    case 'NS':
	  x = oBusca(nom);
      return x.document;
    case 'IE':
	  x = oBusca(nom);
      return x.document;
    case 'MOZ':
      y = window.frames[nom].document;
	  z = oBusca("ojsrs");
	  return window.frames[nom].document;
    case 'OPR':
      var textElement = window.frames[nom].document;
    case 'KONQ':
      var textElement = window.frames[nom].document;
      return textElement;
  }
return "";
}
function contextSetVisibility( vis ){
// vis= true;
  switch( jsrsBrowser ) {
    case 'NS':
      this.container.visibility = (vis)? 'show' : 'hidden';
      this.container.position = (vis)? 'relative' : 'absolute';
      break;
    case 'IE':
      document.all("SPAN" + this.id ).style.display  = (vis)? '' : 'none';
      document.all("SPAN" + this.id ).width          = (vis)? '100' : '0';
      document.all("SPAN" + this.id ).height         = (vis)? '100' : '0';
      document.all("SPAN" + this.id ).style.position = (vis)? 'relative' : 'absolute';
      break;
    case 'MOZ':
      document.getElementById("SPAN" + this.id).style.zIndex 		= (vis)? '100' : '-1';
      document.getElementById("SPAN" + this.id).style.visibility 	= (vis)? 'visible' : 'hidden';
      document.getElementById("SPAN" + this.id).style.position   	= (vis)? 'relative' : 'absolute';
//      document.getElementById("SPAN" + this.id).width   				= (vis)? '250' : '0';
//      document.getElementById("SPAN" + this.id).height  				= (vis)? '100' : '0';
    case 'OPR':
      document.getElementById("SPAN" + this.id).style.visibility = (vis)? 'visible' : 'hidden';
      this.container.width  = (vis)? 250 : 0;
      this.container.height = (vis)? 100 : 0;
      break;
  }
}
// end of context constructor
function jsrsGetContextID(){
  var contextObj;
  for (var i = 1; i <= jsrsContextPoolSize; i++){
    contextObj = jsrsContextPool[ 'jsrs' + i ];
    if ( !contextObj.busy ){
      contextObj.busy = true;
      return contextObj.id;
    }
  }
  // if we got here, there are no existing free contexts
  if ( jsrsContextPoolSize <= jsrsContextMaxPool ){
    // create new context
    var contextID = "jsrs" + (jsrsContextPoolSize + 1);
    jsrsContextPool[ contextID ] = new jsrsContextObj( contextID );
    jsrsContextPoolSize++;
    return contextID;
  } else {
		Anuncio("Sistema Ocupado, espere por favor");
    return null;
  }
}
function jsrsExecute( rspage, callback, func, parms, visibility, mensaje )
{
	//////////////////////////////////////////////////////////////////
	// jsrsExecute('../datosRem.php', escNoticias, 'todasNoticias', pars , false);
	//////////////////////////////////////////////////////////////////
  // call a server routine from client code
  //
  // rspage      - href to asp file
  // callback    - function to call on return
  //               or null if no return needed
  //               (passes returned string to callback)
  // func        - sub or function name to call
  // parms       - string parameter to function
  //               or array of string parameters if more than one
  // visibility  - optional boolean to make container visible for debugging
  // get context

	//parms = asegureParams(parms);

// if (jsrsDisponible())
 {

	if(mensaje != null) Anuncio(mensaje);
	else 	 Anuncio(Mensaje_Loading);
   var contextObj = jsrsContextPool[ jsrsGetContextID() ];
   if(contextObj != null)
   {
   	contextObj.callback = callback;
	   var vis = (visibility == null)? false : visibility;
   	contextObj.setVisibility( vis );
   	if ( jsrsPOST && ((jsrsBrowser == 'IE') || (jsrsBrowser == 'MOZ'))){
     		contextObj.POST( rspage, func, parms );
	   } else {
   	  contextObj.GET( rspage, func, parms );
	   }
  	return contextObj.id;
  	}
  	else { return false; }
 }
}
function jsrsExecutePag( rspage, callback, form, visibility )
{
//   jsrsExecute('../datos.php', escNoticias, 'myForm', false);
  // call a server routine from client code
  //
  // rspage      - href to asp file
  // callback    - function to call on return
  //               or null if no return needed
  //               (passes returned string to callback)
  // form        - name of Formulary to send
  // visibility  - optional boolean to make container visible for debugging
  // get context

// if (jsrsDisponible())
 {
 	 Anuncio(Mensaje_Loading);
   var contextObj = jsrsContextPool[ jsrsGetContextID() ];
   contextObj.callback = callback;
   var vis = (visibility == null)? false : visibility;
   contextObj.setVisibility( vis );
   if ( jsrsPOST && ((jsrsBrowser == 'IE') || (jsrsBrowser == 'MOZ'))){
     contextObj.POSTpage( rspage, form );
   } else {
      // por implementar
     //contextObj.GETpage( rspage, form );
   }
  return contextObj.id;
 }
}
function jsrsExecuteUpLoad( rspage, callback, _input, visibility )
{
//   jsrsExecute('../datos.php', escNoticias, 'myForm', false);
  // call a server routine from client code
  //
  // rspage      - href to asp file
  // callback    - function to call on return
  //               or null if no return needed
  //               (passes returned string to callback)
  // form        - name of Formulary to send
  // visibility  - optional boolean to make container visible for debugging
  // get context

// if (jsrsDisponible())
 {
 	 Anuncio(Mensaje_Loading);
   var contextObj = jsrsContextPool[ jsrsGetContextID() ];
   contextObj.callback = callback;
   var vis = (visibility == null)? false : visibility;
   contextObj.setVisibility( vis );
   if ( jsrsPOST && ((jsrsBrowser == 'IE') || (jsrsBrowser == 'MOZ'))){
     contextObj.POSTupload( rspage, _input );
   } else {
      // por implementar
     //contextObj.GETpage( rspage, form );
   }
  return contextObj.id;
 }
}
function jsrsLoaded( contextID ){

  // get context object and invoke callback
  var contextObj = jsrsContextPool[ contextID ];
  if( contextObj.callback != null){
//Importante
// alert(( contextObj.getPayload() ))
    contextObj.callback( jsrsUnescape( contextObj.getPayload() ), contextID );
  }
  // clean up and return context to pool

  contextObj.callback = null;
  contextObj.busy = false;
/*
  _oPadre = false;
	_oPadre = contextObj.container.parentNode;
	if(_oPadre)
	{
		_oHijo = contextObj.container;
	  _oPadre.removeChild(_oHijo);
	}
  _oPadre = null;
  _oHijo = null;
*/
	window.status="";
//   Anuncio("Cargando...");
}
function jsrsLoadedPag( contextID, obj ){
  // get context object and invoke callback
  var contextObj = jsrsContextPool[ contextID ];
  if( contextObj.callback != null){
    contextObj.callback(  obj , contextID );
  }
  // clean up and return context to pool
  contextObj.callback = null;
  contextObj.busy = false;

/*
	_oPadre = contextObj.container.parentNode;
	if(_oPadre)
	{
		_oHijo = contextObj.container;
	  _oPadre.removeChild(_oHijo)
	  _oPadre = null;
	  _oHijo = null;
	}
*/
  window.status="";
//   Anuncio("...");
}
function jsrsError( contextID, str ){
  alert('jsrsError: '+unescape(str) ); // este alert se debe dejar intacto, pues es el que muestra el error generado por el jsrs
  jsrsContextPool[ contextID ].busy = false
}
function jsrsEscapeQQ( thing ){
	var stmp = String(thing);
//	stmp = String(thing).replace(/'"'/g, '\\"');
	stmp = String(stmp).replace(/'&#47'/g, '//');

	return stmp;
  //return thing.replace(/'"'/g, '\\"');  Commented by xButil
}
function jsrsUnescape( str ){
  // payload has slashes escaped with whacks
  var m = str.replace( /\\\//g, "/" );
  m = m.replace( /\&lt;/g, "<" );
  m = m.replace( /\/\//g, "/" );

  return m;
}
function jsrsBrowserSniff(){
  if (document.layers) return "NS";
  if (document.all) {
		// But is it really IE?
		// convert all characters to lowercase to simplify testing
		var agt=navigator.userAgent.toLowerCase();
		var is_opera = (agt.indexOf("opera") != -1);
		var is_konq = (agt.indexOf("konqueror") != -1);
		if(is_opera) {
			return "OPR";
		} else {
			if(is_konq) {
				return "KONQ";
			} else {
				// Really is IE
				return "IE";
			}
		}
  }
  if (document.getElementById) return "MOZ";
  return "OTHER";
}
/////////////////////////////////////////////////
//
// user functions
function jsrsArrayFromString( s, delim ){
  // rebuild an array returned from server as string
  // optional delimiter defaults to ~
  var d = (delim == null)? '~~~' : delim;
  return s.split(d);
}
function jsrsArrayToString(a, delim){
 // convierte un array en una cadena
  var d = (delim == null)? '~~~' : delim;
  return a.join(d);
}
function jsrsDebugInfo(){
  // use for debugging by attaching to f1 (works with IE)
  // with onHelp = "return jsrsDebugInfo();" in the body tag
  var doc = window.open().document;
  doc.open;
  doc.write( 'Pool Size: ' + jsrsContextPoolSize + '<br><font face="arial" size="2"><b>' );
  for( var i in jsrsContextPool ){
    var contextObj = jsrsContextPool[i];
    doc.write( '<hr>' + contextObj.id + ' : ' + (contextObj.busy ? 'busy' : 'available') + '<br>');
    doc.write( contextObj.container.document.location.pathname + '<br>');
    doc.write( contextObj.container.document.location.search + '<br>');
    doc.write( '<table border="1"><tr><td>' + contextObj.container.document.body.innerHTML + '</td></tr></table>' );
  }
  doc.write('</table>');
  doc.close();
  return false;
}

function jsrsDisponible()
{
 var resultado = false;

 if(jsrsContextPoolSize < jsrsContextMaxPool)
 	{ resultado = true; }
 else
 	{ resultado = false;
 	  Anuncio("Sistema Ocupado, espere por favor");
	}
 return resultado;
}
function jsrsRetorna(str,obj)
{
 var p = document.layers?parentLayer:window.parent;
 if( p.jsrsLoadedPag )  { p.jsrsLoadedPag(str,obj); }
}
function asegureParams(params)
{
/*
	for(_n=0; _n<params.length; _n++)
	{
		if( typeof(params[_n]) == "string")
		{
		alert("1E. " + params[_n]);
         params[_n] = params[_n].replace(/(\n)/g, "-n-");
         params[_n] = params[_n].replace(/(\t)/g, "-t-");
	alert("2E. " + params[_n]);
		}
	}
*/
 return (params);
}
