//PERMITE EXECUTAR JAVASCRIPT NO AJAX
function extraiScript(texto){
    var ini, pos_src, fim, codigo;
    var objScript = null;
    ini = texto.indexOf('<script', 0)
    while (ini!=-1){
        var objScript = document.createElement("script");
        //Busca se tem algum src a partir do inicio do script
        pos_src = texto.indexOf(' src', ini)
        ini = texto.indexOf('>', ini) + 1;

        //Verifica se este e um bloco de script ou include para um arquivo de scripts
        if (pos_src < ini && pos_src >=0){//Se encontrou um "src" dentro da tag script, esta e um include de um arquivo script
            //Marca como sendo o inicio do nome do arquivo para depois do src
            ini = pos_src + 4;
            //Procura pelo ponto do nome da extencao do arquivo e marca para depois dele
            fim = texto.indexOf('.', ini)+4;
            //Pega o nome do arquivo
            codigo = texto.substring(ini,fim);
            //Elimina do nome do arquivo os caracteres que possam ter sido pegos por engano
            codigo = codigo.replace("=","").replace(" ","").replace("\"","").replace("\"","").replace("\'","").replace("\'","").replace(">","");
            // Adiciona o arquivo de script ao objeto que sera adicionado ao documento
            objScript.src = codigo;
        }else{//Se nao encontrou um "src" dentro da tag script, esta e um bloco de codigo script
            // Procura o final do script
            fim = texto.indexOf('</script>', ini);
            // Extrai apenas o script
            codigo = texto.substring(ini,fim);
            // Adiciona o bloco de script ao objeto que sera adicionado ao documento
            objScript.text = codigo;
        }

        //Adiciona o script ao documento
        document.body.appendChild(objScript);
        // Procura a proxima tag de <script
        ini = texto.indexOf('<script', fim);

        //Limpa o objeto de script
        objScript = null;
    }
}


function AjaxReq(url,boxGeral,paramEspera,metodo,param,modo,boxResult,boxErro,processa){
	this.url = url;
	this.boxGeral = boxGeral;
	this.paramEspera = (paramEspera)? true : false;
	this.metodo = (metodo)? metodo : 'GET';
	this.param = (metodo == 'GET')? null : param;
	this.modo = (modo)? modo : 'T';
	this.boxResult = (boxResult)? boxResult : this.boxGeral;
	this.boxErro = (boxErro)? boxErro : this.boxGeral;
	this.processaRes = processa;
	
	this.conectar();
}

AjaxReq.prototype = {
	conectar: function()
	{
		
		if(typeof(this.url)=='undefined' || this.url == ''){
			return false;
		}
		
		this.httpRequest = null;
		
		if(typeof(XMLHttpRequest)!='undefined'){
			this.httpRequest = new XMLHttpRequest();
		}else{
			var axO=['Microsoft.XMLHTTP','Msxml2.XMLHTTP','Msxml2.XMLHTTP.6.0','Msxml2.XMLHTTP.4.0','Msxml2.XMLHTTP.3.0'];
			
			for(var i=0;i<axO.length;i++){ 
				try{ 
						this.httpRequest = new ActiveXObject(axO[i]);
					}
				catch(e){} 
			}
		}
		
		if((typeof(this.httpRequest)!='undefined') || (this.httpRequest != null) || (this.httpRequest != '')){
			var objeto = this;
			this.httpRequest.onreadystatechange = function(){
				objeto.procRetorno.call(objeto);
			}
			this.httpRequest.open(this.metodo,this.url,true);
			if(this.metodo == 'POST'){
				this.httpRequest.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
			}
			
			if(this.metodo == 'GET' && this.modo == 'X'){
				this.httpRequest.setRequestHeader('Content-Type','application/xml');
			}else if(this.metodo == 'GET' && this.modo == 'T'){
				//this.httpRequest.setRequestHeader('Content-Type','application/xhtml+xml');
			}
			this.httpRequest.send(this.param);
		}
	},
	procRetorno: function(){
		if(this.httpRequest.readyState == 1){
			if(this.paramEspera == true){
				this.loading(false,this.boxGeral,true);
			}else if(this.paramEspera == false){
				this.loading(true,this.boxErro,false);
			}
		}
		if(this.httpRequest.readyState == 4){
			if(this.httpRequest.status == 200){
				var resposta = (this.modo == 'T')? this.httpRequest.responseText : this.httpRequest.responseXML;					
				this.loading(false,this.boxErro,false);
				if((typeof(this.processaRes)!='undefined') || (this.processaRes != null) || (this.processaRes != '')){
					extraiScript(resposta);
					this.processaRes(resposta);
				}else{
					extraiScript(resposta);
					alert("Erro: \n"+resposta);
				}
			}else{
				this.processaErro();
			}
		}
	},
	processaErro: function(){
		alert(this.httpRequest.status+" - "+this.httpRequest.statusText+" => "+this.url);
		document.getElementById(this.boxGeral).innerHTML = 'ERRO '+this.httpRequest.status+' - '+this.httpRequest.statusText;
	},
	
	loading: function(c,b,carrega)
	{

		var df = document.getElementById(b);
		if(c == true){
			var i = document.createElement("IMG");
			i.setAttribute("src","/clientes/images/ajax-loading.gif");
			i.setAttribute("id","loading");
			i.setAttribute("width","16");
			i.setAttribute("height","16");
			if(!document.getElementById('loading')){
				df.innerHTML = '&nbsp;';
				df.insertBefore(i, df.firstChild);
			}
		}else if(carrega == true){
			df.innerHTML = '<div style="width:100%; min-height:400px; background:url(http://opusti/hsmuberaba/site2010/js/loading3.gif) center no-repeat;"></div>';
		}else{
			var img = document.getElementById('loading');
			if(img){
				img.parentNode.removeChild(img);
			}else{
				
				df.innerHTML = '&nbsp;';
			}
		}
	}
}
