// JavaScript Document

function BhAjax() {

}

BhAjax.prototype.Req = {
	
	f : {
	}
	
}

BhAjax.prototype.extractScriptTag = function(texto) {
	
	var newText = texto.toString();
	
	while(newText.indexOf("SCRIPT")!=-1) {
		newText = newText.replace("SCRIPT","script");
	}
	
	var ini = 0;
	
    // loop enquanto achar um script
    while (ini!=-1) {
        // procura uma tag de script
        ini = newText.indexOf('<script', ini);

        // se encontrar
        if (ini >=0) {
            // define o inicio para depois do fechamento dessa tag

            ini = newText.indexOf('>', ini) + 1;
            
            // procura o final do script
            var fim = newText.indexOf('</script>', ini);
            // extrai apenas o script
            codigo = newText.substring(ini,fim);

			scriptTag = document.createElement("script");
			
			scriptTag.text=codigo
			
			document.body.appendChild(scriptTag);
			
        }
    }
}

BhAjax.prototype.finishMethod = function(obj,text) {

	if(bh.Util.isNull(obj.fCallBack)) {
	
		alert(text);
		
	}else {	
	
		this.extractScriptTag(text);
		obj.fCallBack(text);
		
	}	
}

BhAjax.prototype.SimpleMethod = function(url,fCallBack,valor){

	/*
		As Parâmetros url,fCall,valor servirão essa classe 
		que está sendo retornada sua instância;
	*/
	
	/*
		Retorna a instância da classe
	*/
	
	return new function() {
		
		/*
			Status do Processo;
			Se a classe se iniciar e não acontecer nenhum erro
			ela retorna true;
		*/
		
		this.statusProcess = true;
		
		this.getStatusProcess = function() {
			return this.statusProcess;
		}
		
		this.access = bh.Ajax.Access;

		this.url = null;
		
		this.setUrl = function(url) {

			if(!bh.Util.isUdf(url) && !bh.Util.isNull(url)) {
				this.url = url;
			}
		}
		
		this.getUrl = function() {
			return this.url;
		}
		
		/*
			Cabeçalhos
		*/
		
		this.header = {	"Content-Type" : "application/x-www-form-urlencoded; charset=utf-8"	};
		
		/*
			Método que seta o tipo request
		*/
		
		this.setMethod = function(m) {
			this.access.setMethod("POST");
		}
		
		/*
			Seta a função que sera chamada para retornar o 
			resultado da página @url do Ajax
		*/

		this.setFCallBack = function(f) {
			this.fCallBack = f;		
		}
		
		/*
			A Variável Post
		*/
		
		this.requestVar = "valor=''";

		this.setRequestVar = function(valor) {
			if(!bh.Util.isUdf(valor) && !bh.Util.isNull(valor)) {
				this.requestVar = "valor="+valor;
			}
		}
		
		/*
			Função que irá ser chamada quando 
			todos os processos forem concluidos
		*/
		
		this.fCallBack = null;

		this.xmlHttp = null;
		
		/*
			Seta o xmlhttp de acordo com o Browser
		*/
		
		this.pXmlHttp = function(){	
			try {
				 this.xmlHttp = new XMLHttpRequest();
			}catch(ee) {
				 try {
					  this.xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
				 }catch(e) {
					  try {
							this.xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
					  }catch(E) {
						  	this.statusProcess = false;
							this.setErro("xml");
							this.xmlHttp = false;
					  }
				 }
			}
		}
		
		/*
			Método serve para retornar o protocolo xmlhttp
		*/
		this.getXmlHttp = function() {
			if(bh.Util.isNull(this.xmlHttp)) {
				this.pXmlHttp();
			}
			return this.xmlHttp;
		}
		
		
		/*
			Tratar Erros
		*/
		
		this.setErro = function(cod) {
			this.erro = cod;
		}
		
		this.erro = null;
		
		this.getErro = function() {
			return this.erro;
		}
		
		this.getMsgErro = function() {
		
			//alert(this.erro.toString().toLowerCase());
			
			switch(this.erro.toString().toLowerCase()) {
				
				case "not found" : 
					msg = "Arquivo Não Encontrado.";
					break;
					
				case "xmlhttp" : 
					msg = "xmlHttp não inicializado.";
					break;
					
				case "url" :
					msg = "Url não definida." ;
					break;
					
				default : 
					msg = "Erro desconhecido.";
					break;
					
			}
			
			return msg;	
			
		}
		
		/*
			Executa o Ajax
		*/
		
		this.run = function() {

			req = this.getXmlHttp();
			
			if(!req) {
				return false;
			}
			
			if(this.access.isPost()) {
				send = this.requestVar;
			} else {
				send = null;
			}

			req.open(this.access.getMethod(), this.getUrl(), true);
			
			for( i in this.header ) {

				req.setRequestHeader(i,this.header[i]);
			}

			req.send(send);
			
			var ajaxCl = this;
			
			// quando ocorrer o evento de mudanca de estado executa a funcao anonima
			req.onreadystatechange = function() {
				// quando o estado for complete (valor 4)
				/*if (req.readyState == 1) {
					//alert('1');
					document.getElementById('produtos').innerHTML = '<img src="adm/ajax/loading.gif">';
				}
			
				if (req.readyState == 2) {
					//alert('2');
					document.getElementById('produtos').innerHTML = '<img src="adm/ajax/loading.gif">';
				}
			
				if (req.readyState == 3) {
					//alert('3');
					document.getElementById('produtos').innerHTML = '<img src="adm/ajax/loading.gif">';
				}*/
				
				if (req.readyState == 4) {
					// se o status for OK 
					if (req.status == 200) {
						// chama a referencia da funcao passada como parametro e joga o resultado que vem do servidor como parametro dela
						
						bh.Ajax.finishMethod(ajaxCl,req.responseText);

					}else {

						ajaxCl.setErro(req.statusText);

						debug = bhDebug();
						
						debug.setMsg(ajaxCl.getMsgErro());
						
						debug.runDebug();

					}

				}
			
			}
		}

		/*
			Setando Alguns Métodos
			
			url,fCall,valor : Parâmetros passados por SimpleMethod
		*/

		this.setUrl(url);

		this.setFCallBack(fCallBack);

		this.setMethod("POST");
		
		this.setRequestVar(valor);
		
		if(bh.Util.isNull(url)) {
			this.statusProcess = false;
			this.setErro("url");
			return false;
		}

		this.pXmlHttp();
	}
}

BhAjax.prototype.Access = {
	
	setUrl : function(u) {
		this.url = u;
	},
	
	setMethod : function(m) {
		this.method = m.toUpperCase();	
	},
	
	getMethod : function() {
		return this.method;
	},
	
	getUrl : function() {
		return this.url;
	},
	
	method : "",
	
	url : "",
	
	isPost : function() {
		return (this.method == "POST");
	},
	
	isGet : function() {
		return (this.method == "GET");
	}
}

BhAjax.prototype.IframeMethod = function(url,fCallBack,form) {
	
	return new function() {
		
		this.method = "POST";
		
		this.getRandomId = function() {
			return "IframeMethod".concat(bh.Util.getRandomId());
		}
	
		this.go = function(iframe,url,form) {
	
			iframe.setAttribute("width","0");
			iframe.setAttribute("height","0");
			iframe.setAttribute("border","0");
			iframe.setAttribute("style","width: 0; height: 0; border: none;");
			
			form.parentNode.appendChild(iframe);
	
			if(bh.Util.Browser.isIe()) {
				window.frames[iframe.getAttribute("id")].name = iframe.getAttribute("id");
			}
			
			form.setAttribute("target",iframe.getAttribute("id"));
			form.setAttribute("action",url);
			form.setAttribute("method",this.method);
			form.setAttribute("enctype","multipart/form-data");
			
			form.submit();
	
			form.setAttribute("target","");
			form.setAttribute("action","");
		}
		
		this.run = function() {

			var url 		= this.url;
			var formulario 	= this.form;
			var iframe 		= bh.Iframe.create(this.getRandomId());
			
			var objInstance = this;
			
			var fRetornaConteudoIframe = function(objIframe) {
				
				var conteudo = "";
				
				if( objIframe.contentWindow.document.documentElement.innerHTML.toUpperCase().indexOf("<SCRIPT")!=-1 ) {
					
					conteudo = objIframe.contentWindow.document.documentElement.innerHTML;
				} else {
					
					conteudo = objIframe.contentWindow.document.body.innerHTML;
				}

				bh.Ajax.finishMethod(objInstance,conteudo);
			}
			
			if( !bh.Util.Browser.isIe() ) {
				iframe.onload = function() {
					fRetornaConteudoIframe(this);
				}				
			} else {
	
				iframe.onreadystatechange = function() {
					if( this.readyState.toLowerCase() == "complete" ) {
						fRetornaConteudoIframe(this);
					}	
				}	
			}
	
			this.go(iframe,url,formulario);
		}

		this.form 		= form;
		this.url 		= url;
		this.fCallBack 	= fCallBack;
	}
}

bh.Ajax = new BhAjax();