/*-----------------------------------------------------------------------------------------------------
** Ajax.js
**-----------------------------------------------------------------------------------------------------
** Alterações: André Valmir em 30/05/2006....Adicionado controle de fila de requisições
**-----------------------------------------------------------------------------------------------------
** Collection of Scripts to allow in page communication from browser to (struts) server
** ie can reload part instead of full page
**
** How to use
** ==========
** 1) Call AjaxHTML from the relevant event on the HTML page (e.g. onclick)
** 2) Pass the url to contact (e.g. Struts Action) and the name of the HTML form to post
** 3) When the server responds ...
**         - the script loops through the response , looking for <span id="name">newContent</span>
**         - each <span> tag in the *existing* document will be replaced with newContent
**
** NOTE: <span id="name"> is case sensitive. Name *must* follow the first quote mark and end in a quote
**         Everything after the first '>' mark until </span> is considered content.
**         Empty Sections should be in the format <span id="name"></span>
**--------------------------------------------------------------------------------------------------*/
FilaAjax     = [];      //Fila de conexões
iFilaAjax    = 0;
xmlhttp      = false;   //transport
bErroCarrega = false;   //xmlhttp.status != 200
bDebug       = false;

if (!Array.prototype.trim) {
   String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };
}


//-------------------------------------------------------------------------------------------------
if (!Array.prototype.indexOf) {
     Array.prototype.indexOf = function(elt /*, from*/) {
         var len  = this.length;
         var from = Number(arguments[1]) || 0;
         from = (from < 0)
              ? Math.ceil(from)
              : Math.floor(from);
         if (from < 0) {
            from += len;
         }
         for (; from < len; from++) {
             if (from in this &&
                this[from] === elt)
             return from;
         }
         return -1;
     };
}

/**
 *   Array convenience method to remove element.
 *
 *   @param object element
 *   @returns boolean
 */
Array.prototype.remove = function (element) {
	var result = false;
	var array = [];
	for (var i = 0; i < this.length; i++) {
		if (this[i] == element) {
			result = true;
		} else {
			array.push(this[i]);
		}
	}
	this.clear();
	for (var i = 0; i < array.length; i++) {
		this.push(array[i]);
	}
	array = null;
	return result;
};


function AjaxIniciar() {
    var oHttpRequest = false;
    var msxmlhttp = new Array(
                  'Microsoft.XMLHTTP' ,
                  'Msxml2.XMLHTTP'    ,
                  'Msxml2.XMLHTTP.7.0',
                  'Msxml2.XMLHTTP.6.0',
                  'Msxml2.XMLHTTP.5.0',
                  'Msxml2.XMLHTTP.4.0',
                  'Msxml2.XMLHTTP.3.0' );

    if(typeof XMLHttpRequest != "undefined") {
       oHttpRequest = new XMLHttpRequest();
    }else{
       for (var i = 0; i < msxmlhttp.length && !oHttpRequest; i++) {
          try {
              oHttpRequest = new ActiveXObject(msxmlhttp[i]);
          } catch (e) {
              oHttpRequest = false;
          }
       }
    }

    //verifica se o browser tem suporte a ajax
    if(!oHttpRequest) {
       alert("Esse browser não tem recursos para uso do Ajax");
    }

    return oHttpRequest;
}


/*-------------------------------------------------------------------*/
function pegaElementoPorId( id ) {
    var obj;
    obj = document.getElementById( id );
    for (var x = 0; !obj && x <= document.forms.length-1; x++ ) {
        for (var y = 0; !obj && y <= document.forms[x].elements.length-1; y++ ) {
            if (document.forms[x].elements[y].name == id) {
               obj = document.forms[x].elements[y];
            }
        }
    }
    return obj;
}

/*-------------------------------------------------------------------*/
function mudouCodPai(chavePai,idCampo) {
    var objCampo = pegaElementoPorId( idCampo );   //document.getElementById( idCampo );
    if (chavePai) {
       chavePai = String(chavePai);
       if (chavePai != '')  {
          if (objCampo.options.length > 0) {
             if (objCampo.options[0].value == ('*' + chavePai)) {
                if (objCampo.length > 1) {
                   return false;
                }
             }
          }
       }
    }
    return true;
}

/*-------------------------------------------------------------------*/
function ajaxSelect( url, idCampo, codDefault, chavePai, msgErro ) {
     var objCampo = pegaElementoPorId( idCampo );   //document.getElementById( idCampo );
     var ajax     = AjaxIniciar();
     var iDefault = 0;
     var i        = 0;

     if (!mudouCodPai(chavePai, idCampo)) {
         return true;
     }

     objCampo.options.length = 0;
     objCampo.options[i]     = new Option("Aguarde...", 0 );
     objCampo.selectedIndex  = i;

     msgErro = msgErro ? msgErro : 'Nenhum registro cadastrado.';

     ajax.open("GET", url, true);

     ajax.onreadystatechange = function() {
        if (ajax.readyState == 1) {
            objCampo.disabled = true;
        }
        else if ( ajax.readyState == 4) {
            if(ajax.responseText == false) {
                objCampo.options[0] = new Option("Erro!",0);
                objCampo.selectedIndex = 0;
            }
            else if (ajax.responseText == 'xxx') {
                objCampo.options[0] = new Option(msgErro,0);
                objCampo.selectedIndex = 0;
            }
            else {
                var r = ajax.responseText;
                var codigoPai = '';

                if (chavePai) {
                     codigoPai = '*' + String(chavePai);
                }

                total = r.substring(0, (d = r.indexOf(';')));
                r = r.substring(++d);

                objCampo.options.length  = 0;
                objCampo.options[i] = new Option("Aguarde...", codigoPai );
                i++;

                while ( i <= total ) {

                    val = r.substring(0, (d = r.indexOf(':')));
                    r = r.substring(++d);
                    txt = r.substring(0, (d = r.indexOf(';')));
                    r = r.substring(++d);

                    objCampo.options[i] = new Option(txt,val);

                    if ( codDefault && val )  {
                       if (Number(val)==Number(codDefault)) {
                          iDefault = i;
                       }
                    }

                    i++;
                }
                objCampo.options[0].text = "";
                objCampo.selectedIndex = iDefault;
                objCampo.disabled = false;
            }
            objCampo.disabled = false;
        }
     }
     ajax.send(null);
}

/*-------------------------------------------------------------------*/
function findPosXLayerAjax(obj) {
    var curleft = 0;
    if (obj.offsetParent) {
        while (obj.offsetParent) {
            curleft += obj.offsetLeft;
            obj = obj.offsetParent;
        }
    } else if (obj.x)
        curleft += obj.x;
    //alert( curleft );
    return curleft;
}

function findPosYLayerAjax(obj)  {
    var curtop = 0;
    if (obj.offsetParent) {
        while (obj.offsetParent) {
            curtop += obj.offsetTop;
            obj = obj.offsetParent;
        }
    }
    else if (obj.y)
        curtop += obj.y;
    //alert( curtop );
    return curtop;
}

function showLayerAjax( nameLayer, id ) {
    var objHint = pegaElementoPorId( nameLayer );  //document.getElementById( nameLayer );
    var obj = ((typeof(id)).toLowerCase()=="string") ? pegaElementoPorId( id ) : id;

    objHint.style.top   = findPosYLayerAjax(obj) + 30 + 'px';  //50
    objHint.style.left  = findPosXLayerAjax(obj) + 9  + 'px';

    //var tags = document.all.tags('SELECT'); //<-- isso não funciona no IE
    var tags = document.getElementsByTagName("SELECT");
    for( var i=0; i < tags.length ; i++ ) {
        tags[i].style.visibility = "hidden";
    }
    objHint.style.visibility = "visible";
}

function hideLayerAjax( nameHint, id ) {
    var objHint = pegaElementoPorId( nameHint );  //document.getElementById( nameHint );
    //var tags    = document.all.tags('SELECT');  //<-- isso não funciona no IE
    var tags    = document.getElementsByTagName("SELECT");

    for( var i=0; i < tags.length ; i++ ) {
        tags[i].style.visibility = "visible";
    }

    objHint.style.visibility = "hidden";

    if (id) {
       var obj = pegaElementoPorId(id);   //document.getElementById(id);
       if (obj) {
          obj.focus();
       }
    }
}

/*-------------------------------------------------------------------
** ( Serialize the form elements )
** gets the contents of the form as a URL encoded String
** suitable for appending to a url
** @param formName to encode
** @return string with encoded form values , beings with &
**------------------------------------------------------------------*/
function getFormValues(formName) {
    var formElements;
    var field        = "";
    var fieldType    = "";
    var value        = "";
    var returnString = "";
    var bOk          = true;

    if( formName ) {
        formElements = document.forms[formName].elements; //Pega os valores do form

        //build a string containing every field on the passed form
        for ( var i=formElements.length-1; i>=0; --i ) {
            bOk       = true;
            field     = formElements[i];
            fieldType = field.type.toLowerCase();

            if (fieldType != "checkbox" && fieldType != "radio" ) {
                 value = field.value;
            }else {
                 bOk   = field.checked;
                 value = field.value;
            }

            //we escape (encode) each value
            if (bOk) {
                returnString = returnString + "&" + escape(field.name) + "=" + escape(value);
            }
        }
    }
    return returnString;
}

/**
  ScriptFragment: '(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)',
  extractScripts: function() {
    var matchAll = new RegExp(Prototype.ScriptFragment, 'img');
    var matchOne = new RegExp(Prototype.ScriptFragment, 'im');
    return (this.match(matchAll) || []).map(function(scriptTag) {
      return (scriptTag.match(matchOne) || ['', ''])[1];
    });
  },
**/
/*
function extractScripts( txt ) {
  var ScriptFragment = '(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)'
  var matchAll = new RegExp(Prototype.ScriptFragment, 'img');
  var matchOne = new RegExp(Prototype.ScriptFragment, 'im');
  return (this.match(matchAll) || []).map(function(scriptTag) {
    return (scriptTag.match(matchOne) || ['', ''])[1];
  });
}
*/

/*-------------------------------------------------------------------
** Splits the text into <span> elements
** @param 1: the text to be parsed, 2: elements
** @return array of <span> elements - this array can contain nulls
** splitTextIntoElement( resultado, 'span;div' );
**------------------------------------------------------------------*/
function splitTextIntoElement(textToSplit, nomeElement ) {
     var retornoArray;
     var elementArray = nomeElement.split(';');

     for (var x=elementArray.length-1; x>=0; --x ) {

         //Split the document
         elementArray[x] = String(elementArray[x]).toLowerCase();
         returnElements  = textToSplit.split("</" + elementArray[x] + ">");

         //Process each of the elements
         for ( var i=returnElements.length-1; i>=0; --i ) {

             //Remove everything before the 1st span
             spanPos = returnElements[i].indexOf("<" + elementArray[x] );

             //if we find a match , take out everything before the span
             if(spanPos>0) {
                 subString         = returnElements[i].substring(spanPos);
                 returnElements[i] = subString;
             }
         }
         if (spanPos > 0) {
            if (retornoArray) {
                retornoArray = retornoArray.concat( returnElements );
            }else {
                retornoArray = returnElements.splice(0, returnElements.length);
            }
         }
     }

     if (!retornoArray) {
        retornoArray = Array(0);
     }

     return retornoArray;
}


/*-------------------------------------------------------------------
** Replace html elements in the existing (ie viewable document)
** with new elements (from the ajax requested document)
** WHERE they have the same name AND are <span> elements
** @param newTextElements (output of splitTextIntoSpan)
**                    in the format <span id=name>texttoupdate
**------------------------------------------------------------------*/
function replaceExistingWithNewHtml(newTextElements) {
    var obj;
    var ary = new Array( 'span', 'div' );

    //loop through newTextElements
    for ( var j=ary.length-1; j>=0; --j ) {
        for ( var i=newTextElements.length-1; i>=0; --i ) {
            //alert( newTextElements[i] );
            //check that this begins with <span
            if(newTextElements[i].indexOf("<" + ary[j])>-1) {
                //get the name - between the 1st and 2nd quote mark
                startNamePos = newTextElements[i].indexOf('"')+1;
                endNamePos   = newTextElements[i].indexOf('"',startNamePos);
                name         = newTextElements[i].substring(startNamePos,endNamePos);

                //get the content - everything after the first > mark
                startContentPos = newTextElements[i].indexOf('>')+1;
                content         = newTextElements[i].substring(startContentPos);
                obj             = pegaElementoPorId(name);  //document.getElementById(name);

                //Now update the existing Document with this element
                put(obj,content);
            }
        }
    }
}


function put(obj,valor,msg) { //coloca o valor na variavel/elemento de retorno
    var sMsg = "Aguarde...";
    if (msg) {
       sMsg = msg;
    }
    if (obj) {
        if((typeof(obj)).toLowerCase()=="string") { //se for o nome da string
            if(valor!="Falha no carregamento") {
                eval(obj + '= unescape("' + escape(valor) + '")')
            }
        }else if(obj.tagName.toLowerCase()=="input") {
            valor     = escape(valor).replace(/\%0D\%0A/g,"")
            obj.value = unescape(valor);
        }else if(obj.tagName.toLowerCase()=="select") {
            select_innerHTML(obj, valor)
        }else if(obj.tagName) {
            if( valor.indexOf(sMsg)>=0 ) {
                obj.innerHTML = '<b>' + valor + '</b>';
            } else {
                obj.innerHTML = valor;
            }
        }
    }
}


/*-------------------------------------------------------------------*/
function Ajax_Run() {
    var params;
    var url        = antiCacheRand( FilaAjax[iFilaAjax][0] );   //url
    var objId      = getById( FilaAjax[iFilaAjax][2] );         //idCampo
    var objMsg     = getById( FilaAjax[iFilaAjax][3] );         //idMsg
    var doFunction = FilaAjax[iFilaAjax][4];                    //pFunction
    var assincrono = FilaAjax[iFilaAjax][5];                    //assincrono
    var sMsg       = "Aguarde...";     //Carregando ...  //"<center><span class='linha'><b>Por favor aguarde...</b></span></center>"

    //se não existir o objeto xmlhttp ele será criado com o método iniciar
    if (!xmlhttp) {
        xmlhttp = AjaxIniciar();
    }

    //se tiver suporte ajax faz a chamada
    if (xmlhttp) {

        //if (bDebug) alert( '5 teste');

        //Mostra a mensagem "Aguarde..."
        put( objMsg, sMsg);

        //get the (form based) params to push up as part of the get request
        params = 'acao=ajax';
        if (FilaAjax[iFilaAjax][1]) {
             params = params + getFormValues( FilaAjax[iFilaAjax][1] );  //nameOfFormToPost
        }

        //callback will be an anonymous function that calls back into our class
        //this allows the call back in which we handle the response (_processStateChange())
        // to have the correct scope.
        //xmlhttp.open("GET", url + xSep + params, true);
        xmlhttp.open("POST", url, assincrono);
        //xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
        xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=ISO-8859-1');
        xmlhttp.setRequestHeader("Content-length", params.length);
        xmlhttp.setRequestHeader('Cache-Control', 'no-store, no-cache, must-revalidate');
        xmlhttp.setRequestHeader('Cache-Control', 'post-check=0, pre-check=0');
        xmlhttp.setRequestHeader('Pragma', 'no-cache');

        if(assincrono) {
           xmlhttp.onreadystatechange = function() { processStateChange(); };
        }

        ///alert(params);

        xmlhttp.send(params);

        if(!assincrono) {
           processStateChange();
        }

        return true;

    } else {

        return false;

    }

    function processStateChange() {
        var resultado;
        var spanElements;

        //enquanto estiver processando...emite a msg de Aguarde
        if (xmlhttp.readyState == 1) {
             if (getTagName(objMsg) == "select") {
                 objMsg.disabled = true;
             }
             put( objMsg, sMsg);
        }

        //após ser processado - pega o retorno e atualiza a página
        if (xmlhttp.readyState == 4) {
             if(xmlhttp.status == 200) {

                 resultado = this.xmlhttp.responseText;

                 if ( resultado.indexOf(" ")<0 ) {
                    resultado = resultado.replace(/\+/g," "); //substituindo os + por espaços mesma coisa que usar urldecode() do php
                 }
                 resultado = unescape( resultado );           //descomente esta linha se tiver usado o urlencode no php ou asp

                 if (getTagName(objMsg) != "select") {
                    put( objMsg, "");
                 }

                 if (objId) {
                    put( objId, resultado );
                 }

                 spanElements = splitTextIntoElement( resultado, 'span;div' );  //Split the text response into Span elements
                 replaceExistingWithNewHtml(spanElements);                      //Use these span elements to update the page

                 if (bDebug) {
                     //alert( 'resultado: ' + resultado );
                 }

                 if (getTagName(objMsg) == "select") {
                     objMsg.disabled = false;
                 }

                 if (doFunction) {
                    doFunction( resultado );
                 }

                 extraiScript(resultado);

             }else {
                 bErroCarrega = true;
                 if(objMsg) {
                     put( objMsg, "Falha no carregamento. " + httpStatus(xmlhttp.status) );
                 } else if (bDebug) {
                     alert( "Falha no carregamento. " + httpStatus(xmlhttp.status)  );
                 }
             }

             //Roda o próximo da Fila
             iFilaAjax = iFilaAjax + 1;
             if(iFilaAjax<FilaAjax.length) {
                 setTimeout("Ajax_Run()",20);
             }else {
                 FilaAjax  = new Array();
                 iFilaAjax = 0;
                 //alert('fim:' + iFilaAjax);
             }
        }
    }

    function getTagName( obj ) {
        var retorno;
        if (obj) {
           if((typeof(obj)).toLowerCase()!="string") {
              retorno = obj.tagName.toLowerCase();
           }
        }
        return retorno;
    }

    function getById( id ) {
        var obj;
        if (id) {
            obj = document.getElementById( id );
            for (var x = 0; !obj && x <= document.forms.length-1; x++ ) {
                for (var y = 0; !obj && y <= document.forms[x].elements.length-1; y++ ) {
                    if (document.forms[x].elements[y].name == id) {
                       obj = document.forms[x].elements[y];
                    }
                }
            }
        }
        return obj;
    }

    function httpStatus(stat){ //retorna o texto do erro http
        switch(stat){
            case   0: return "Erro desconhecido de javascript";
            case 400: return "400: Solicita&ccedil;&atilde;o incompreensível"; break;
            case 403: case 404: return "404: N&atilde;o foi encontrada a URL solicitada"; break;
            case 405: return "405: O servidor n&atilde;o suporta o m&eacute;todo solicitado"; break;
            case 500: return "500: Erro desconhecido de natureza do servidor"; break;
            case 503: return "503: Capacidade m&aacute;xima do servidor alcançada"; break;
            default: return "Erro " + stat + ". Mais informa&ccedil;&otilde;es em http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html"; break;
        }
    }
}


/*-----------------------------------------------------------------------------------
* select_innerHTML - altera o innerHTML de um select independente se é FF ou IE
* Corrige o problema de não ser possível usar o innerHTML no IE corretamente
* Veja o problema em: http://support.microsoft.com/default.aspx?scid=kb;en-us;276228
* Use a vontade mas coloque meu nome nos créditos. Dúvidas, me mande um email.
* Versão: 1.0 - 06/04/2006
* Autor: Micox - Náiron José C. Guimarães - micoxjcg@yahoo.com.br
* Parametros:
* objeto(tipo object): o select a ser alterado
* innerHTML(tipo string): o novo valor do innerHTML
**----------------------------------------------------------------------------------*/
function select_innerHTML(objeto, innerHTML) {

    if (bErroCarrega ) {
        alert( innerHTML );    //"Falha no carregamento."
        objeto.options[0] = new Option("", "");
    }else if( innerHTML.toLowerCase().indexOf("aguarde")>=0 ) {
        objeto.options[0]    = new Option("Aguarde...", "");
        objeto.selectedIndex = 0;
    }
    else if( innerHTML.toLowerCase().indexOf("<option")>=0 ) {
        selectOption();
    }
    else {
        selectList();
    }

    function selectOption() {
        var opt;
        var selTemp = document.createElement("micoxselect")

        objeto.innerHTML = ""
        selTemp.id       = "micoxselect1"
        document.body.appendChild(selTemp)
        selTemp               = document.getElementById("micoxselect1")
        selTemp.style.display = "none"
        if(innerHTML.toLowerCase().indexOf("<option")<0){//se não é option eu converto
            innerHTML = "<option>" + innerHTML + "</option>"
        }
        innerHTML         = innerHTML.replace(/<option/g,"<span").replace(/<\/option/g,"</span")
        selTemp.innerHTML = innerHTML
        for(var i=0;i<selTemp.childNodes.length;i++){
            if(selTemp.childNodes[i].tagName){
                opt = document.createElement("OPTION")
                for(var j=0;j<selTemp.childNodes[i].attributes.length;j++){
                    opt.setAttributeNode(selTemp.childNodes[i].attributes[j].cloneNode(true))
                }
                opt.value = selTemp.childNodes[i].getAttribute("value")
                opt.text  = selTemp.childNodes[i].innerHTML
                if(document.all){ //IEca
                    objeto.add(opt)
                }else{
                    objeto.appendChild(opt)
                }
            }
        }
        document.body.removeChild(selTemp)
        selTemp = null
    }


    function selectList() {
        if(innerHTML == false || innerHTML == 'xxx') {
           objeto.options.length = 1;
           objeto.options[0] = new Option("",0);
        }
        else {
           var i = 0;
           var d;
           var val;
           var txt;
           var total;
           var codPai;
           var codAtual;
           var iSelected = 0;
           var r = innerHTML;
           var sMsg;

           total    = (r.split('|')).length - 3;

           r        = r + '|';
           codPai   = r.substring(0, (d = r.indexOf('|')));
           r        = r.substring(++d);

           codAtual = r.substring(0, (d = r.indexOf('|')));
           r        = r.substring(++d);

           sMsg = r.substring(0, (d = r.indexOf('|')));
           r    = r.substring(++d);

           codPai   = codPai.trim();
           codAtual = codAtual.trim();

           objeto.options.length = 1;
           objeto.options[0]     = new Option("Aguarde...", codPai );
           i++;

           while ( i <= total ) {

               val = r.substring(0, (d = r.indexOf('¦')));  //':'
               r   = r.substring(++d);

               txt = r.substring(0, (d = r.indexOf('|')));  //';'
               r   = r.substring(++d);

               val = val.trim();
               txt = txt.trim();

               objeto.options[i] = new Option(txt, val);

               if ( (codAtual != '') && (val != '' ) ) {
                  if (Number(val)==Number(codAtual)) {
                     iSelected = i;
                  }
               }

               i++;
           }

           objeto.options[0].text = sMsg;
           objeto.selectedIndex   = iSelected;
        }
        objeto.disabled = false;
    }
}


/*-----------------------------------------------------------------------------------
* Maravilhosa função feita pelo SkyWalker.TO do imasters/forum
* http://forum.imasters.com.br/index.php?showtopic=165277&
**----------------------------------------------------------------------------------*/
function extraiScript(texto) {
    // inicializa o inicio ><
    var ini = 0;
    var fim;

    // loop enquanto achar um script
    while (ini!=-1){
        ini = texto.indexOf('<script', ini);      // procura uma tag de script

        // se encontrar
        if (ini >=0){
            ini = texto.indexOf('>', ini) + 1;      // define o inicio para depois do fechamento dessa tag
            fim = texto.indexOf('</script>', ini);  // procura o final do script
            codigo = texto.substring(ini,fim);      // extrai apenas o script
            // executa o script
            /**
            novo = document.createElement("script")
            novo.text = codigo;
            document.body.appendChild(novo);
            ***/
            var scriptTag = document.getElementById('meuScriptAdicionado');
            var head      = document.getElementsByTagName('head').item(0)
            if(scriptTag) {
               head.removeChild(scriptTag);
            }
            script      = document.createElement('script');
            script.id   = 'meuScriptAdicionado';
            script.text = codigo;
            head.appendChild(script);
        }
    }
}

/*-----------------------------------------------------------------------------------*/
function antiCacheRand(aurl) {
      var dt    = new Date();
      var xRand = encodeURI(Math.random() + "_" + dt.getTime());
      var xSep  = (aurl.indexOf("?")>=0) ? "&" : "?";
      return aurl + xSep + xRand;
}

/*-----------------------------------------------------------------------------------*/
function atualizaCampoAjax(id,xValue) {
    var obj = pegaElementoPorId(id);    //document.getElementById(id);
    if (obj) {
        try {
           //alert( obj.id + ' = ' + xValue );
           obj.value = xValue;
        }catch(e) {
           //alert( "erro:" + e.description );
        }
    }
}

function AjaxHTML( url, nameOfFormToPost, idCampo, idMsg, xbDebug ) {
  bDebug = xbDebug;
  //alert( bDebug + '   url=' + url );
  Ajax_HTML(url, nameOfFormToPost, null, idMsg );
}

/*-----------------------------------------------------------------------------------*/
function Ajax_HTML( url, nameOfFormToPost, idCampo, idMsg, pFunction, assincrono) {
   assincrono = (arguments.length >= 6) ? assincrono : true;
   //Adiciona à fila
   FilaAjax[FilaAjax.length] = [url, nameOfFormToPost, idCampo, idMsg, pFunction, assincrono];

    //Se não há conexões pendentes, executa
   if((iFilaAjax+1)==FilaAjax.length) {
       Ajax_Run();
   }

}



