//Fila de conexões - Variaveis globais
fila=[];
ifila=0;

//Mostra imagem de loading enquanto chama a pagina requisitada
function imagem(){
// Var objImg é uma flag que verifica a existência do objeto imagem do Ajax
// Caso essa variavel seja true ela passa a ser true
   var boImg   = new Boolean(false);
// Verifica a Existência do frame principal
    if(window.parent){
// Verifica se a imagem existe no frame principal
      if(window.parent.document.getElementById("carregando")){
       var loading = window.parent.document.getElementById("carregando");
       boImg = true;
      }
// Verifica se a imagem existe no formulário ativo
    }else if(document.getElementById("carregando")){
       var loading = document.getElementById("carregando");
       boImg = true;
    }
// Verifica se a imagem já existe na tela
// Caso exista ela verifica seu display alterando para o seu aparecimento ou não.
    if(boImg==true){
      if(loading.style.display=="block"){
        loading.style.display="none";
      }else{
        loading.style.display="block";
      }
    }
}

function ajax(stPagina,stCtrl,stId){
	try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } 
    	catch(e) { try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
			catch(ex) { try { xmlhttp = new XMLHttpRequest(); }
	    		catch(exc) { alert("Esse browser não tem recursos para uso do Ajax");
           		xmlhttp = null;
            }
       	}
	}
  	//se tiver suporte ajax
  	if(xmlhttp) {	
		//Mostra imagem de loading enquanto chama a pagina requisitada
		imagem();
		//Abre a url
		stCtrl = "&stCtrl="+stCtrl;
	//    stParametros = "<?=$sessao->id?>"+stCtrl;
		stLink = stPagina+stCtrl;
		xmlhttp.open("GET", stLink ,true);
		xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=iso-8859-1;");
	
		//Executada quando o navegador obtiver o código
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4){
				//Lê o texto
				var texto = xmlhttp.responseText
				//Exibe o texto no div conteúdo
				var conteudo = window.parent.document.getElementById(stId);
				conteudo.innerHTML = texto;
				imagem();
			}
		}
		xmlhttp.send(null)
	  }
}

function executaJavaScript( stJs ) {
    imagem();
    var d = document;
    var f = window.parent ? window.parent.document.form : document.form;
    try {
        eval( stJs );
    } catch( err ) {
      if(window.parent){
        window.parent.document.getElementById("spnErro").innerHTML = "<p align='center'><br><b>Erro: </b>"+err.name+": "+err.message+"<pre><p align='left'><b>Exibindo página gerada pelo oculto:</b><br><br>"+stJs+"<br></pre>";
        window.parent.document.getElementById("spnErro").style.display = 'block';
	eval( stJs );
      }
    }finally{
       imagem();
    }
}

function ajaxJavaScript( stPagina, stCtrl ) {
    stCtrl = "&stCtrl="+stCtrl;
    stLink = stPagina+stCtrl;
    //Adiciona à fila
    fila[fila.length]=stLink;
    //Se não há conexões pendentes, executa
    if( (ifila+1) == fila.length ) {
        ajaxJavaScriptRun();
    }
}
    

//Executa a próxima conexão da fila
function ajaxJavaScriptRun(){
	try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } 
    	catch(e) { try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
			catch(ex) { try { xmlhttp = new XMLHttpRequest(); }
	    		catch(exc) { alert('Esta página utiliza recursos Ajax, que seu navegador não tem suporte.\n Acesse: http://www.getfirefox.com');
           		xmlhttp = null;
            }
       	}
	}
  	//se tiver suporte ajax
  	if(xmlhttp) {	
		imagem();
		//Abre a conexão
		xmlhttp.open("GET",fila[ifila],true);
		//Função para tratamento do retorno
		xmlhttp.onreadystatechange=function() {
			if (xmlhttp.readyState==4){
				//Lê o texto
				var texto = xmlhttp.responseText;
				//Executa o texto como um javaScript
				executaJavaScript( texto );
				//Roda o próximo
				ifila++;
				if( ifila < fila.length ) {
					ajaxJavaScriptRun();
				}
			  imagem();
			}
		}
		//Executa
		xmlhttp.send(null);
	}
}

//Verifica se existe algum processo em andamento, se não executa de forma sincrona.
function ajaxJavaScriptSincrono( stPagina, stCtrl ) {
    stCtrl = "&stCtrl="+stCtrl;
    stLink = stPagina+stCtrl;
    if( (ifila) == fila.length ) {
		try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } 
    	catch(e) { try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
			catch(ex) { try { xmlhttp = new XMLHttpRequest(); }
	    		catch(exc) { alert('Esta página utiliza recursos Ajax, que seu navegador não tem suporte.\n Acesse: http://www.getfirefox.com');
           		xmlhttp = null;
            }
       	}
		}
		//se tiver suporte ajax
		if(xmlhttp) {	
			imagem();
			//Abre a conexão
			xmlhttp.open("GET",stLink,false);
			//Executa
			xmlhttp.send(null);
			//Recebe
			var texto = xmlhttp.responseText;
			//Executa o texto como um javaScript
			executaJavaScript( texto );
			//Retira a imagem loading
			imagem();
		} else alert('Esta página utiliza recursos Ajax, que seu navegador não tem suporte.\n Acesse: http://www.getfirefox.com');
    } else alert('Aguarde todos os processos concluírem.');
}

function executaFuncaoAjax( funcao, parametrosGET, sincrono ) {
    stPaginaProcessamento = 'funcoes_ajax.php';
    if( parametrosGET ) stLink = stPaginaProcessamento +'?'+parametrosGET;
    else stLink = stPaginaProcessamento;

    if( sincrono ) ajaxJavaScriptSincrono( stLink, funcao )
    else ajaxJavaScript( stLink, funcao );
}

function montaParametrosGET( funcao, campos, sincrono  ) {
    var stLink = '';
    var f = document.frmAjax;
    var d = document;

    if( campos ) {
        if ( campos.search(/,/) > 0 ) {
            arCampos = campos.split(",");
        } else {
            arCampos = new Array();
            arCampos[0] = campos;
        }
        for( i=0 ; i<arCampos.length ; i++ ) {
            stCampo = eval( 'document.getElementById(\''+arCampos[i]+'\')' );
            if( typeof(stCampo) == 'object' ){
                if ( stCampo[0] ){              
                     if ( stCampo[0].type == 'radio' ) {
                         for( j=0; j<stCampo.length; j++ ) {
                             if( stCampo[j].checked == true ) {
                                 stLink += '&'+arCampos[i]+'='+trim( stCampo[j].value );
                             }
                         }
                     } else {
                         stLink += '&'+arCampos[i]+'='+stCampo.value;
                     }
                } else {
                    if(stCampo.type == 'checkbox' ){
                        if( stCampo.checked == true ){
                            stLink+= '&'+arCampos[i]+'='+stCampo.value;
                        }
                    }else{
                        stLink+= '&'+arCampos[i]+'='+stCampo.value;
                    }
                }
            }
        }
    } else {
        for( i=0 ; i<f.elements.length ; i++) {
            if( typeof(f.elements[i]) == 'object' ){               
                if( f.elements[i].type == 'radio' || f.elements[i].type == 'checkbox' ){
                    if( f.elements[i].checked == true ){
                        stLink += '&'+f.elements[i].id+'='+f.elements[i].value;
                    }
                }else{
                    stLink += '&'+f.elements[i].id+'='+f.elements[i].value;
                }
            }
        }
    }
    executaFuncaoAjax( funcao, stLink, sincrono );
}
