/******************************************************************************************************************/
/* FUNÇÃO INICIAL *************************************************************************************************/
/******************************************************************************************************************/

	//Teste do tipo de browser pra ver se tem a biblioteca XMLHttpRequest e qual usar
	try{
		xmlhttp3 	= new XMLHttpRequest();
		xmlhttp2 	= new XMLHttpRequest();
		xmlhttp 	= new XMLHttpRequest();
    }catch(ee){
        try{
            xmlhttp3	= new ActiveXObject("Msxml2.XMLHTTP");
            xmlhttp2	= new ActiveXObject("Msxml2.XMLHTTP");
			xmlhttp 	= new ActiveXObject("Msxml2.XMLHTTP");
        }catch(e){
            try{
                xmlhttp3	= new ActiveXObject("Microsoft.XMLHTTP");
                xmlhttp2	= new ActiveXObject("Microsoft.XMLHTTP");	
				xmlhttp 	= new ActiveXObject("Microsoft.XMLHTTP");
			}catch(E){
                xmlhttp3	= false;
                xmlhttp2	= false;
                xmlhttp 	= false;
            }
        }
    }


/******************************************************************************************************************/
/* FUNÇOES AJAX ***************************************************************************************************/
/******************************************************************************************************************/

	var msgError = "Seu navegador não suporta alguns recursos deste site. Por favor atualize-o\nSugestão: http://www.mozilla.com/firefox/"

	/* Fila de conexões */
	var fila=[]
	var ifila=0

	//Executa a próxima conexão da fila
	function ajaxRun(){
		if(xmlhttp2){
			//Abre a conexão
			xmlhttp2.open("GET",fila[ifila][1]+"&"+Math.random(),true);
			//Função para tratamento do retorno
			xmlhttp2.onreadystatechange=function() {
				if (xmlhttp2.readyState==4){
					//Mostra o HTML recebido
					retorno=unescape(xmlhttp2.responseText.replace(/\+/g," "))
					document.getElementById(fila[ifila][0]).innerHTML=retorno
					//Roda o próximo
					ifila++
					if(ifila<fila.length)setTimeout("ajaxRun()",20)
				}
			}
			//Executa
			xmlhttp2.send(null)
		}else{
			alert(msgError)
		}
	}

/*******************************************************************/

	//Carrega conteudo o passado na URL para o DIV usando XMLHTTPREQUEST
	function retornaConteudo(url,div){
			//Carregando...
			g = top.document.getElementById(div);
			g.innerHTML = "<div align='center'><img src='img/icon/ajax-loader.gif'/></div>";//'<div class="aguarde">Carregando dados...</div>';

			//Adiciona à fila
			fila[fila.length]=[div,url]

			//Se não há conexões pendentes, executa
			if((ifila+1)==fila.length)ajaxRun()
	}


	function loadReprUF(obj){
		var uf = obj.options[obj.selectedIndex].value;
		document.getElementById("reprs").innerHTML = '';
		if(uf == 'todos'){
			retornaConteudo('representantes.loadCidade.php?c=todas&s=todos','reprs');
			retornaConteudo('representantes.loadUF.php?c=0','div_cidade');
		} else {
			retornaConteudo('representantes.loadUF.php?c='+uf,'div_cidade');
		}
	}

	function loadReprCidade(obj,uf){
		if(obj=='todas'){
			var cidade = 'todas';
		} else if(obj == 'unica'){
			var tmp = uf
			var uf = 'unica'
			var cidade = tmp;
		} else {
			var cidade = obj.options[obj.selectedIndex].value;
			var uf = document.getElementById("cbo_uf").options[document.getElementById("cbo_uf").selectedIndex].value;
		}
		document.getElementById("reprs").innerHTML = '';
		retornaConteudo('representantes.loadCidade.php?c='+cidade+'&s='+uf,'reprs');
	}



/* ALTERA PARAMETRO POR AJAX */
function swapParam(campo, tabela, tipo, id){
		if(xmlhttp){
			url = "adm.ajax.swapParam.php?campo="+campo+"&tabela="+tabela+"&id="+id+"&tipo="+tipo+"&"+Math.random();
			xmlhttp.open("GET", url,true);
			xmlhttp.onreadystatechange=function() {
				if (xmlhttp.readyState==4){
					resposta=xmlhttp.responseText
					document.getElementById(id+"-"+campo).innerHTML = resposta;
				}
			}
			//Enquanto ocorre a conexao e busca, mostra o texto nos campos...
			document.getElementById(id+"-"+campo).innerHTML = "<img src='img/icon/ajax-loader.gif'/>";//"&bull;&bull;&bull;";
			xmlhttp.send(null)
		}else{
			//Caso o navegador nao suporte XMLHttpRequest
			alert("Seu navegador não suporta algumas funcionalidades deste site.")
		}
}



/* ALTERA VALOR DE TEXTBOX POR AJAX */
function alterValue(obj,cod,tbl,field,div,acao){
		if(xmlhttp){
			url = "adm.ajax.changeValue.php?tbl="+tbl+"&field="+field+"&cod="+cod+"&newV="+obj.value+"&acao="+acao+"&"+Math.random();

			xmlhttp.open("GET", url,true);
			xmlhttp.onreadystatechange=function() {
				if (xmlhttp.readyState==4){
					resposta=xmlhttp.responseText
					document.getElementById(div).innerHTML = resposta;
				}
			}
			//Enquanto ocorre a conexao e busca, mostra o texto nos campos...
			document.getElementById(div).innerHTML = "aguarde...";
			xmlhttp.send(null)
		}else{
			//Caso o navegador nao suporte XMLHttpRequest
			alert("Seu navegador não suporta algumas funcionalidades deste site.")
		}
}


  /****************************/
 /* RETORNA CESTA DE PEDIDOS */
/****************************/
function retornaCesta(){
		if(top.document.getElementById("cestaPrd")){
			f = top.document.getElementById("cestaPrd");
			if(xmlhttp){
				var url="produtos.loadCesta.php"
				xmlhttp.open("GET", url,true);
				xmlhttp.onreadystatechange=function() {
					if (xmlhttp.readyState==4){
						resposta=xmlhttp.responseText
						f.innerHTML = resposta;
					}
				}
				f.innerHTML = "<br/><div class='aguarde'>Aguarde<br/>Carregando cesta...</div><br/>";
				xmlhttp.send(null)
			}else{
				alert(msgError)
			}
		}
}




  /****************************/
 /* EXIBE IMAGEM CLICADA     */
/****************************/
/* ALTERA PARAMETRO POR AJAX */
function showPic(id){
		if(xmlhttp){
			url = "produtos.view.imagem.php?id="+id+"&"+Math.random();
			xmlhttp.open("GET", url,true);
			xmlhttp.onreadystatechange=function() {
				if (xmlhttp.readyState==4){
					resposta=xmlhttp.responseText
					document.getElementById("imgGrd").innerHTML = resposta;
					document.getElementById("lnkDownImg").innerHTML = "<a href='download.prd.php?id="+id+"' target='frmProcessa'><img src='img/icon/download.gif'/></a>";
				}
			}
			//Enquanto ocorre a conexao e busca, mostra o texto nos campos...
			document.getElementById("imgGrd").innerHTML = "<img src='img/icon/ajax-loader.gif'/>";//"&bull;&bull;&bull;";
//			setTimeout(exxxxx,1500,xmlhttp);
			xmlhttp.send(null);
		}else{
			//Caso o navegador nao suporte XMLHttpRequest
			alert("Seu navegador não suporta algumas funcionalidades deste site.")
		}
}

function exxxxx(obj){
	obj.send(null)
}


function loadOrcRepr(obj,div,tmp){
	if(obj == null){
		var valor = tmp;
	} else {
		var valor = obj.options[obj.selectedIndex].value;
	}
	retornaConteudo('orcamento.load.'+div+'.php?c='+valor,'div_'+div);
}


function submitBusca(){
	if(xmlhttp){
		tipoA = document.getElementById("tipoA").checked;
		tipoO = document.getElementById("tipoO").checked;
		valor = document.getElementById("txt").value;
		div = 'buscaResult';
		url = "busca.do.php?txt="+valor+"&a="+tipoA+"&o="+tipoO+"&"+Math.random();
		xmlhttp.open("GET", url,true);
		xmlhttp.onreadystatechange=function() {
			if (xmlhttp.readyState==4){
				resposta=xmlhttp.responseText
				document.getElementById(div).innerHTML = resposta;
			}
		}
		//Enquanto ocorre a conexao e busca, mostra o texto nos campos...
		document.getElementById(div).innerHTML = "Aguarde...<br/><img src='img/icon/ajax-loader.gif'/>";//"&bull;&bull;&bull;";
		xmlhttp.send(null)
	}else{
		//Caso o navegador nao suporte XMLHttpRequest
		alert("Seu navegador não suporta algumas funcionalidades deste site.")
	}
}
