/* 
		
		ajxDestroy - Classe Ajax by Caio Augusto =D
		Versão : 0.1
*/
//Função Construtora
function ajxDestroy(pMetodo){
	
	this.strMetodo = pMetodo.toUpperCase();
	this.xmlHttp = this.instanciaAjax();
	
}
//Definindo os prototypes
ajxDestroy.prototype = {
	//Função que instancia cada xmlHttp
	instanciaAjax: function() {
		var xmlHttp = null;
		try {
			xmlHttp = new XMLHttpRequest();
		} catch (e) {
			var arrProgs = ['MSXML2.XMLHTTP','Microsoft.XMLHTTP','MSXML2.XMLHTTP.5.0','MSXML2.XMLHTTP.4.0','MSXML2.XMLHTTP.3.0'];
			var isHabil = false;
			for (var i = 0; (i < arrProgs.length) && ( ! isHabil); i ++) {
				try {
					xmlHttp = new ActiveXObject(arrProgs[i]);
					isHabil = true;
				} catch (e) {}
			}
			if ( ! isHabil ) {
				alert('Esse browser não suporta recursos AJAX');
				return null;
			}
		}
		return xmlHttp;
	},
	//Função que executa os javascripts que estiverem em uma página ajax
	funcionaScript: function(pTexto) {
		var ini, pos_src, fim, codigo;
		var objScript = null;
		ini = pTexto.indexOf('<script', 0);
		//
		while (ini!=-1){
			var objScript = document.createElement("script");
			pos_src = pTexto.indexOf(' src', ini)
			ini = pTexto.indexOf('>', ini) + 1;
			//
			if (pos_src < ini && pos_src >=0) {
				ini = pos_src + 4;
				fim = pTexto.indexOf('.', ini)+4;
				codigo = pTexto.substring(ini,fim);
				codigo = codigo.replace("=","").replace(" ","").replace("\"","").replace("\"","").replace("\'","").replace("\'","").replace(">","");
				objScript.src = codigo;
			}
			else {
				fim = pTexto.indexOf('</script>', ini);
				codigo = pTexto.substring(ini,fim);
				objScript.text = codigo;
			}
			document.body.appendChild(objScript);
			ini = pTexto.indexOf('<script', fim);
			objScript = null;
		}
	},
	//Muda Método
	mudaMetodo: function(pMetodo) {
		this.strMetodo = pMetodo.toUpperCase(); 
	},
	//Renova uma instância xmlHttp
	renovaInstancia: function() {
		this.xmlHttp = this.instanciaAjax();
	},
	//Esta função retorna para um innerHTML o resultado
	mostraConteudo: function(pParametros,pValores,pAction,pRetorno,pCancela,pTempo) {
		//Setando as variáveis internas
		var _arrParametros = pParametros.split(",");
		var _arrValores = pValores.split(",");
		var _strAcao = pAction;
		var _numTempo = Number(pTempo) == null ? 0 : Number(pTempo);
		var _strRetorno = String(pRetorno);
		var _isCancela = Boolean(pCancela);
		var _strMetodo = this.strMetodo;
		//Criando referencias para as funções não se perderem
		var fncFuncionaScript = this.funcionaScript;
		//Preenchendo os Valores e os Parametros
		var strRequestString = "";
		for (var i=0; i<_arrParametros.length;i++){
			
			strRequestString += _arrParametros[i] + "=" + _arrValores[i];
			((i != (_arrParametros.length -1)) ? strRequestString += "&" : strRequestString +="" );
			
		}
		//Mostra o Carregador
		//Verifica se deve abortar a chamada anterior
		((_isCancela == true) ? this.xmlHttp.abort() : "" );
		//Referencia
		var xmlHttp = this.xmlHttp;
		/*
		//Arrumando os Charsets
		xmlHttp.setRequestHeader('Content-Length', _strAcao.length);
		xmlHttp.setRequestHeader('Content-Type', 'text/plain; charset=UTF-8');
		xmlHttp.setRequestHeader('Accept-Charset', 'UTF-8');
		*/
		//Verifica o Método e envia as variáveis da forma certa
		var numTimeOut = setTimeout( 
		function(){
			clearTimeout(numTimeOut);
			if(this.strMetodo == "POST"){
				xmlHttp.open(_strMetodo, _strAcao , true);
				//Desabilita Cache
				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");
				xmlHttp.setRequestHeader('Content-Type',"application/x-www-form-urlencoded;");
				xmlHttp.send("ajx=1&"+strRequestString);
			} else {
				xmlHttp.open(_strMetodo, _strAcao+"?"+strRequestString, true);
				xmlHttp.send("ajx=1");
			}
			xmlHttp.onreadystatechange = function() {
				switch(xmlHttp.readyState){
					case 0:
						//Não iniciou o request
					case 1:
						//O request foi setado
					break;
					case 2:
						//O request foi enviado
					break;
					case 3:
						//O request está em progresso
					break;
					case 4:
						//O request está completo
						//FechaCarregador;
						if(xmlHttp.status == 200){
							//O Request veio certo
							document.getElementById(_strRetorno).innerHTML = xmlHttp.responseText; // retorna o valor em text
							fncFuncionaScript(xmlHttp.responseText);
						} else {
							//Aconteceu algum erro no request
							document.getElementById(_strRetorno).innerHTML = "Ocorreu o seguinte erro no servidor : " + xmlHttp.statusText;
						}
						//
					break;
				}
			}
		},_numTempo);			
	},
	//Essa função executa um ajax mas não faz nenhum tipo de retorno, só envia
	executaScript: function(pParametros,pValores,pAction,pCancela,pTempo,pErro) {
		//Setando as variáveis internas
		var _arrParametros = pParametros.split(",");
		var _arrValores = pValores.split(",");
		var _strAcao = pAction;
		var _numTempo = Number(pTempo) == null ? 0 : Number(pTempo);
		var _isCancela = Boolean(pCancela);
		var _strMetodo = this.strMetodo;
		var _strErro = pErro;
		//Preenchendo os Valores e os Parametros
		var strRequestString = "";
		for (var i=0; i<_arrParametros.length;i++){
			
			strRequestString += _arrParametros[i] + "=" + _arrValores[i];
			((i != (_arrParametros.length -1)) ? strRequestString += "&" : strRequestString +="" );
			
		}
		//Verifica se deve abortar a chamada anterior
		((_isCancela == true) ? this.xmlHttp.abort() : "" );
		//Referencia
		var xmlHttp = this.xmlHttp;
		//
		var numTimeOut = setTimeout( 
		function(){
			clearTimeout(numTimeOut);
			if(this.strMetodo == "POST"){
				xmlHttp.open(_strMetodo, _strAcao , true);
				//Desabilita Cache
				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");
				xmlHttp.setRequestHeader('Content-Type',"application/x-www-form-urlencoded;");
				xmlHttp.send("ajx=1&"+strRequestString);
			} else {
				xmlHttp.open(_strMetodo, _strAcao+"?"+strRequestString, true);
				xmlHttp.send("ajx=1");
			}
			xmlHttp.onreadystatechange = function() {
				switch(xmlHttp.readyState){
					case 0:
						//Não iniciou o request
					case 1:
						//O request foi setado
					break;
					case 2:
						//O request foi enviado
					break;
					case 3:
						//O request está em progresso
					break;
					case 4:
						//O request está completo
						//FechaCarregador;
						if(xmlHttp.status == 200){
							//O Request veio certo
							//Executou Corretamente mas não faz nada
						} else {
							//Aconteceu algum erro no request
							document.getElementById(_strErro).innerHTML = "Ocorreu o seguinte erro no servidor : " + xmlHttp.statusText;
						}
						//
					break;
				}
			}
		},_numTempo);	
	}
	,
	//Essa função executa um javascript e retorna o valor para outra função especificada
	//pelo desenvolvedor
	executaCallback: function(pParametros,pValores,pAction,pFuncao,pCancela,pTempo,pErro) {
		
		//Setando as variáveis internas
		var _arrParametros = pParametros.split(",");
		var _arrValores = pValores.split(",");
		var _strAcao = pAction;
		var _numTempo = Number(pTempo) == null ? 0 : Number(pTempo);
		var _isCancela = Boolean(pCancela);
		var _strMetodo = this.strMetodo;
		var _strErro = pErro;
		var _strFuncao = pFuncao;
		//Preenchendo os Valores e os Parametros
		var strRequestString = "";
		for (var i=0; i<_arrParametros.length;i++){
			
			strRequestString += _arrParametros[i] + "=" + _arrValores[i];
			((i != (_arrParametros.length -1)) ? strRequestString += "&" : strRequestString +="" );
			
		}
		//Verifica se deve abortar a chamada anterior
		((_isCancela == true) ? this.xmlHttp.abort() : "" );
		//Referencia
		var xmlHttp = this.xmlHttp;
		//
		var numTimeOut = setTimeout( 
		function(){
			clearTimeout(numTimeOut);
			if(this.strMetodo == "POST"){
				xmlHttp.open(_strMetodo, _strAcao , true);
				//Desabilita Cache
				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");
				xmlHttp.setRequestHeader('Content-Type',"application/x-www-form-urlencoded;");
				xmlHttp.send("ajx=1&"+strRequestString);
			} else {
				xmlHttp.open(_strMetodo, _strAcao+"?"+strRequestString, true);
				xmlHttp.send("ajx=1");
			}
			xmlHttp.onreadystatechange = function() {
				switch(xmlHttp.readyState){
					case 0:
						//Não iniciou o request
					case 1:
						//O request foi setado
					break;
					case 2:
						//O request foi enviado
					break;
					case 3:
						//O request está em progresso
					break;
					case 4:
						//O request está completo
						//FechaCarregador;
						if(xmlHttp.status == 200){
							//O Request veio certo
							//Executou Corretamente mas não faz nada
							pFuncao(xmlHttp.responseText);
						} else {
							//Aconteceu algum erro no request
							document.getElementById(_strErro).innerHTML = "Ocorreu o seguinte erro no servidor : " + xmlHttp.statusText;
						}
						//
					break;
				}
			}
		},_numTempo);
		
	},
	//Função que busca todos os campos e valores de um formulário e envia pra página AJAX
	enviaFormulario: function(pFormulario,pAction,pRetorno,pCancela,pTempo) {
		//Setando as variáveis internas
		var _arrElementos = pFormulario.elements;
		var _strAcao = pAction;
		var _numTempo = Number(pTempo) == null ? 0 : Number(pTempo);
		var _strRetorno = String(pRetorno);
		var _isCancela = Boolean(pCancela);
		if (pFormulario.method != "" ){
			var _strMetodo = pFormulario.method;
		} else {
			var _strMetodo = this.strMetodo;
		}
		//Criando referencias para as funções não se perderem
		var fncFuncionaScript = this.funcionaScript;
		//Preenchendo os Valores e os Parametros
		var strRequestString = "";
		for (var i=0; i<_arrElementos.length;i++){
 
			if(_arrElementos[i].name!="") {
  			strRequestString += _arrElementos[i].name + "=" + _arrElementos[i].value;
  			((i != (_arrElementos.length -1)) ? strRequestString += "&" : strRequestString +="" );
   }
		}
  //Mostra o Carregador
		//Verifica se deve abortar a chamada anterior
		((_isCancela == true) ? this.xmlHttp.abort() : "" );
		//Referencia
		var xmlHttp = this.xmlHttp;
		/*
		//Arrumando os Charsets
		xmlHttp.setRequestHeader('Content-Length', _strAcao.length);
		xmlHttp.setRequestHeader('Content-Type', 'text/plain; charset=UTF-8');
		xmlHttp.setRequestHeader('Accept-Charset', 'UTF-8');
		*/
		//Verifica o Método e envia as variáveis da forma certa
		var numTimeOut = setTimeout( 
		function(){
			clearTimeout(numTimeOut);
			if(_strMetodo == "post"){
  		xmlHttp.open(_strMetodo,_strAcao,true);
				//Desabilita Cache
		 	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");
				xmlHttp.setRequestHeader('Content-Type',"application/x-www-form-urlencoded;");
    xmlHttp.send("ajx=1&"+strRequestString);
			} else {
				xmlHttp.open(_strMetodo,_strAcao+"?"+strRequestString, true);
				xmlHttp.send("ajx=1");
			}
			xmlHttp.onreadystatechange = function() {
				switch(xmlHttp.readyState){
					case 0:
						//Não iniciou o request
					case 1:
						//O request foi setado
					break;
					case 2:
						//O request foi enviado
					break;
					case 3:
						//O request está em progresso
					break;
					case 4:
						//O request está completo
						//FechaCarregador;
						if(xmlHttp.status == 200){
							;
							//O Request veio certo
							document.getElementById(_strRetorno).innerHTML = xmlHttp.responseText; // retorna o valor em text
							fncFuncionaScript(xmlHttp.responseText);
						} else {
							//Aconteceu algum erro no request
							document.getElementById(_strRetorno).innerHTML = "Ocorreu o seguinte erro no servidor : " + xmlHttp.statusText;
						}
						//
					break;
				}
			}
		},_numTempo);	
	},
	//Função que preenche um ComboBox
	preencheCombo: function(pCombo,pParametros,pValores,pAction,pCancela,pTempo,pErro) {
		//Setando as variáveis internas
		var _arrParametros = pParametros.split(",");
		var _arrValores = pValores.split(",");
		var _strAcao = pAction;
		var _numTempo = Number(pTempo) == null ? 0 : Number(pTempo);
		var _strRetorno = String(pErro);
		var _isCancela = Boolean(pCancela);
		var _objCombo = pCombo;
		var _strMetodo = "GET";
		//Preenchendo os Valores e os Parametros
		var strRequestString = "";
		for (var i=0; i<_arrParametros.length;i++){
			
			strRequestString += _arrParametros[i] + "=" + _arrValores[i];
			((i != (_arrParametros.length -1)) ? strRequestString += "&" : strRequestString +="" );
			
		}
		//Mostra o Carregador
		_objCombo.options.length = 0;
		var novoOpt = document.createElement("option");
		novoOpt.setAttribute("id", "opcoes");
		novoOpt.value = "0";
		novoOpt.text  = "Carregando...";
		_objCombo.options.add(novoOpt);
		//Verifica se deve abortar a chamada anterior
		((_isCancela == true) ? this.xmlHttp.abort() : "" );
		//Referencia
		var xmlHttp = this.xmlHttp;
		/*
		//Arrumando os Charsets
		xmlHttp.setRequestHeader('Content-Length', _strAcao.length);
		xmlHttp.setRequestHeader('Content-Type', 'text/plain; charset=UTF-8');
		xmlHttp.setRequestHeader('Accept-Charset', 'UTF-8');
		*/
		//Verifica o Método e envia as variáveis da forma certa
		var numTimeOut = setTimeout( 
		function(){
			clearTimeout(numTimeOut);
			if(this.strMetodo == "POST"){
				xmlHttp.open(_strMetodo, _strAcao , true);
				//Desabilita Cache
				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");
				xmlHttp.setRequestHeader('Content-Type',"application/x-www-form-urlencoded;");
				xmlHttp.send("ajx=1&"+strRequestString);
			} else {
				xmlHttp.open(_strMetodo, _strAcao+"?"+strRequestString, true);
				xmlHttp.send("ajx=1");
			}
			xmlHttp.onreadystatechange = function() {
				switch(xmlHttp.readyState){
					case 0:
						//Não iniciou o request
					case 1:
						//O request foi setado
					break;
					case 2:
						//O request foi enviado
					break;
					case 3:
						//O request está em progresso
					break;
					case 4:
						//O request está completo
						//FechaCarregador;
						if(xmlHttp.status == 200){
							xmlRetorno = xmlHttp.responseXML;
							var arrXML   = xmlRetorno.getElementsByTagName("opt");
							if(arrXML.length > 0) {
								_objCombo.options.length = 0;
								 for(var i = 0 ; i < arrXML.length ; i++) {
									var item = arrXML[i];
									var codigo    =  item.getElementsByTagName("valor")[0].firstChild.nodeValue;
									var descricao =  item.getElementsByTagName("descricao")[0].firstChild.nodeValue;
									//_objCombo.innerHTML = "--Selecione uma das opções abaixo--";
									var novoOpt = document.createElement("option");
									novoOpt.setAttribute("id", "opcoes");
									novoOpt.value = codigo;
									novoOpt.text  = descricao;
									_objCombo.options.add(novoOpt);
								 }
							  }
							  else {
								//caso o XML volte vazio, printa a mensagem abaixo
								document.getElementById(_strRetorno).innerHTML = "--XML vazio!!!--";
							  }	  
							
						} else {
							//Aconteceu algum erro no request
							document.getElementById(_strRetorno).innerHTML = "Ocorreu o seguinte erro no servidor : <strong>" + xmlHttp.statusText + "</strong>";
						}
						//
					break;
				}
			}
		},_numTempo);
		
	},
	fechaPreview: function(pPreview){
		document.onmousemove="";
		document.getElementById(pPreview).style.display = "none";
	},
	//Traz um preview com os dados 
	fazPreview: function(pPreview,pParametros,pValores,pAction,pCancela) {
		//Variáveis
		var _arrParametros = pParametros.split(",");
		var _arrValores = pValores.split(",");
		var _strAcao = pAction;
		var _isCancela = Boolean(pCancela);
		var _strMetodo = this.strMetodo;
		//Criando referencias para as funções não se perderem
		var fncFuncionaScript = this.funcionaScript;
		//Preenchendo os Valores e os Parametros
		var strRequestString = "";
		for (var i=0; i<_arrParametros.length;i++){
			
			strRequestString += _arrParametros[i] + "=" + _arrValores[i];
			((i != (_arrParametros.length -1)) ? strRequestString += "&" : strRequestString +="" );
			
		}
		//Verifica se deve abortar a chamada anterior
		((_isCancela == true) ? this.xmlHttp.abort() : "" );
		//Referencia
		var xmlHttp = this.xmlHttp;
		
		
		//Calcula o Tamanho da tela
		var offsetfrommouse=[15,25];
		var displayduration=0;
		
		var defaultimageheight = document.getElementById(pPreview).offsetHeight;
		var defaultimagewidth = document.getElementById(pPreview).offsetWidth;
		
		var objTamTela = (!window.opera && document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body;
		var numWidth=document.all? objTamTela.scrollLeft+objTamTela.clientWidth : pageXOffset+window.innerWidth - offsetfrommouse[0];
		var numHeight=document.all? Math.max(objTamTela.scrollHeight, objTamTela.clientHeight) : Math.min(window.innerHeight);
		if( (navigator.userAgent.indexOf("Konqueror")==-1  || navigator.userAgent.indexOf("Firefox")!=-1 || (navigator.userAgent.indexOf("Opera")==-1 && navigator.appVersion.indexOf("MSIE")!=-1)) && (numWidth>650 && numHeight>500)) {
		
		//( width == 0 ) ? width = defaultimagewidth: '';
		//( height == 0 ) ? height = defaultimageheight: '';
		if(this.strMetodo == "POST"){
				xmlHttp.open(_strMetodo, _strAcao , true);
				//Desabilita Cache
				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");
				xmlHttp.setRequestHeader('Content-Type',"application/x-www-form-urlencoded;");
				xmlHttp.send("ajx=1&"+strRequestString);
			} else {
				xmlHttp.open(_strMetodo, _strAcao+"?"+strRequestString, true);
				xmlHttp.send("ajx=1");
			}
			xmlHttp.onreadystatechange = function() {
				switch(xmlHttp.readyState){
					case 0:
						//Não iniciou o request
					case 1:
						//O request foi setado
					break;
					case 2:
						//O request foi enviado
					break;
					case 3:
						//O request está em progresso
					break;
					case 4:
						//O request está completo
						//FechaCarregador;
						if(xmlHttp.status == 200){
							//O Request veio certo
							document.getElementById(pPreview).innerHTML = xmlHttp.responseText; // retorna o valor em text
							fncFuncionaScript(xmlHttp.responseText);
						} else {
							//Aconteceu algum erro no request
							document.getElementById(pPreview).innerHTML = "Ocorreu o seguinte erro no servidor : " + xmlHttp.statusText;
						}
						//
					break;
				}
			}
		/*width+=30
		height+=55
		defaultimageheight = height
		defaultimagewidth = width*/
			document.onmousemove= function(pMouse) {
				var xcoord=offsetfrommouse[0]
				var ycoord=offsetfrommouse[1]
		
				var docwidth=document.all? objTamTela.scrollLeft+objTamTela.clientWidth : pageXOffset+window.innerWidth-15
				var docheight=document.all? Math.max(objTamTela.scrollHeight, objTamTela.clientHeight) : Math.min(window.innerHeight)
			
				if (typeof pMouse != "undefined"){
					if (docwidth - pMouse.pageX < defaultimagewidth + 2*offsetfrommouse[0]){
						xcoord = pMouse.pageX - xcoord - defaultimagewidth; // Move pro lado esquerdo do cursor
					} else {
						xcoord += pMouse.pageX;
					}
					if (docheight - pMouse.pageY < defaultimageheight + 2*offsetfrommouse[1]){
						ycoord += pMouse.pageY - Math.max(0,(2*offsetfrommouse[1] + defaultimageheight + pMouse.pageY - docheight - objTamTela.scrollTop));
					} else {
						ycoord += e.pageY;
					}
			
				} else if (typeof window.event != "undefined"){
					if (docwidth - event.clientX < defaultimagewidth + 2*offsetfrommouse[0]){
						xcoord = event.clientX + objTamTela.scrollLeft - xcoord - defaultimagewidth; // Move pro lado esquerdo do cursor
					} else {
						xcoord += objTamTela.scrollLeft+event.clientX
					}
					if (docheight - event.clientY < (defaultimageheight + 2*offsetfrommouse[1])){
						ycoord += event.clientY + objTamTela.scrollTop - Math.max(0,(2*offsetfrommouse[1] + defaultimageheight + event.clientY - docheight));
					} else {
						ycoord += objTamTela.scrollTop + event.clientY;
					}
				}
				document.getElementById(pPreview).style.display = "block";
				document.getElementById(pPreview).style.position = "absolute";
				document.getElementById(pPreview).style.left=(xcoord-20)+"px"
				document.getElementById(pPreview).style.top=(ycoord-20)+"px"
			}
		
		}
		
	},
	//Função que autoCompleta
	autoCompleta: function(pCampo,pParametros,pValores,pAction,pTempo,pCancela) {
		
		
		
	}
}

/*
QUANDO TESTAR VERIFICAR SE AS VARIÁVEIS CHEGAM CERTAS COM DIFERENTES MÉTODOS

GET
http_request.open('GET', 'http://www.dominio.com.br/arquivo.extensao', true);
http_request.send(null);

POST
http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

DETONA CACHE
http_request.setRequestHeader("Cache-Control","no-store, no-cache, must-revalidate");
http_request.setRequestHeader("Cache-Control","post-check=0, pre-check=0");
http_request.setRequestHeader("Pragma", "no-cache");

DEFINE FORMATOS
xmlHttp.setRequestHeader('Content-Length', url.length);
xmlHttp.setRequestHeader('Content-Type', 'text/plain; charset=UTF-8');
xmlHttp.setRequestHeader('Accept-Charset', 'UTF-8');
*/
