/******************************************************************************************************************/
/* 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()
	}





/* 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,id,tabela,campo,div,acao){
		if(xmlhttp){
			url = "adm.ajax.changeValue.php?tabela="+tabela+"&campo="+campo+"&id="+id+"&newValue="+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.")
		}
}


/* CARREGA COMBO DA CALCULADORA */
function loadCombo(obj, tipo){
		valor = obj.value;
		if(xmlhttp){
			url = "calculadora."+tipo+".php?valor="+valor+"&"+Math.random();
			xmlhttp.open("GET", url,true);
			xmlhttp.onreadystatechange=function() {
				if (xmlhttp.readyState==4){
					resposta=xmlhttp.responseText;
					document.getElementById("div-"+tipo).innerHTML = resposta;
				}
			}
			//Enquanto ocorre a conexao e busca, mostra o texto nos campos...
			document.getElementById("div-"+tipo).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.")
		}
}

function execCalc(){
		tipo = "resultado";

		// produto
		produto = document.getElementById("PRODUTO").value;
		if(produto == '0'){ alert("selecione um PRODUTO"); return false; }
		// superficie
		tmpSup	= document.getElementById("SUPERFICIE").value;
		if(tmpSup == '0'){ alert("selecione uma SUPERFÍCIE"); return false; }
		tmpSup	= tmpSup.split("|");
		sup		= tmpSup[0];
		min		= tmpSup[1];
		med		= tmpSup[2];
		max		= tmpSup[3];

		// rendimento
		rend	= document.getElementById("RENDIMENTO").value;
		if(rend == '0'){ alert("selecione um RENDIMENTO"); return false; }

		// area
		area	= document.getElementById("AREA").value;
		if(area.length < 1){ alert("informe a ÁREA"); return false; }

		// unidade medida
		un1 = document.getElementById("un-M").checked;
		un2 = document.getElementById("un-S").checked;
		if(un1 == true){
			unidade = "M";
		} else {
			unidade = "S";
		}
		
		if(xmlhttp){
			url = "calculadora.exec.php?produto="+produto+"&sup="+sup+"&min="+min+"&med="+med+"&max="+max+"&rend="+rend+"&area="+area+"&unidade="+unidade+"&"+Math.random();
			xmlhttp.open("GET", url,true);
			xmlhttp.onreadystatechange=function() {
				if (xmlhttp.readyState==4){
					resposta=xmlhttp.responseText;
					document.getElementById("div-"+tipo).innerHTML = resposta;
					retornaConteudo("calculadora.exiborc.php?a=1","div-orcamento");
				}
			}
			//Enquanto ocorre a conexao e busca, mostra o texto nos campos...
			document.getElementById("div-"+tipo).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.")
		}

}

/* ADICIONA CALCULO AO ORÇAMENTO */
function addOrcamento(prd,area){
		if(xmlhttp){
			url = "calculadora.addorc.php?prd="+prd+"&area="+area+"&"+Math.random();
			xmlhttp.open("GET", url,true);
			xmlhttp.onreadystatechange=function() {
				if (xmlhttp.readyState==4){
					resposta=xmlhttp.responseText;
					document.getElementById("avisoOrc").innerHTML = resposta;
					retornaConteudo("calculadora.exiborc.php?a=1","div-orcamento");
				}
			}
			//Enquanto ocorre a conexao e busca, mostra o texto nos campos...
			document.getElementById("avisoOrc").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.")
		}
}

/** FUNÇÕES ESPECÍFICAS DO PROJETO **************************************/

function loadFuncAtivas(obj){
		valor = obj.value;
		tmp = document.getElementById("aviso2").innerHTML;
		if(  tmp == 'Aguarde<br><img src="img/icon/ajax-loader.gif">') {
//			alert("Aguarde processamento");
			return false;
		}
		if(xmlhttp){
			url = "adm.grupofuncao.loadFuncAtivas.php?c="+valor+"&"+Math.random();
			xmlhttp.open("GET", url,true);
			xmlhttp.onreadystatechange=function() {
				if (xmlhttp.readyState==4){
					resposta=xmlhttp.responseText;
					document.getElementById("div_fnc").innerHTML = resposta;
					document.getElementById("aviso2").innerHTML = "";
					document.getElementById("cbo_grp").disabled = false;
				}
			}
			//Enquanto ocorre a conexao e busca, mostra o texto nos campos...
			document.getElementById("aviso2").innerHTML = "Aguarde<br/><img src='img/icon/ajax-loader.gif'/>";
			document.getElementById("cbo_grp").disabled = true;
			document.getElementById("aviso").innerHTML = "";
			xmlhttp.send(null)
		}else{
			//Caso o navegador nao suporte XMLHttpRequest
			alert("Seu navegador não suporta algumas funcionalidades deste site.")
		}
}


function gravarFuncAtivas(){
	// grupo
	grupo = document.getElementById('cbo_grp').value;
	if(grupo.length < 1 || grupo == ''){
		alert("Selecione um grupo");
		return false;
	}

	// funcoes
	funcoes = document.getElementById('cbo_fnc');
	sel_funcoes = '';
	for (var i = 0; i < funcoes.length; i++) {
		if (funcoes.options[i].selected == true) {
			sel_funcoes = sel_funcoes +  funcoes.options[i].value +',' ;
		}
	}
	url = 'adm.grupofuncao.gravaFuncAtivas.php?g='+grupo+'&f='+sel_funcoes+'&'+Math.random();
	div = 'aviso';
	retornaConteudo(url,div);
}