/****************************************************************************************
* VARIÁVEIS GLOBAIS */
var xmlhttp = null; // Objeto XMLHttpRequest
var func; // variável que armazena a função que será executada quando o readyState mudar
var cache  = new Array(); // cache para requisições Ajax
var cacheUrl;
var boolExec;
/****************************************************************************************
* DIV PARA FEEDBACK AO USUÁRIO */
document.write ("<div name=\"divFeedBackAjax\" id=\"divFeedBackAjax\" class=\"arial11preto\" style=\"position: absolute; top: 0px; left: 0px; width: 100px; background: #ffffff; display: none; text-align: center; border: solid #000000 1px;\"><br>&nbsp;&nbsp;Processando...&nbsp;&nbsp;<br><br></div>");
var divFeedBack = document.getElementById("divFeedBackAjax");

function mostraFeedBack() {
	if (divFeedBack) {
		divFeedBack.style.left = (screen.width / 2) - 50;
		divFeedBack.style.top = document.body.scrollTop + 20;
		divFeedBack.style.display = "";
	}
}

function ocultaFeedBack() {
	if (divFeedBack)
		divFeedBack.style.display = "none";
}

/****************************************************************************************
* FUNÇÃO QUE INICIA O PROCESSO DO AJAX
* ------------------------------------
* Parâmetros:
* url : qual a url que o objeto ira abrir	deve conter todas os parâmetros que a página irá receber.
* f		:	qual função ira executar após a abertura do objeto xml. [ver funcao executaFuncao()]
*/
function startAjax(url, f)
{
  //func = f;
	loadXMLDoc(url, f);
}


/****************************************************************************************
 FUNÇÃO PARA CRIAR A ABRIR O OBJETO XMLHttpRequest
* -------------------------------------------------------------
* É chamada pela function startAjax();
*/

function loadXMLDoc(url, f) {
	if (!xmlhttp) {
		if (window.XMLHttpRequest){
			xmlhttp=new XMLHttpRequest();
			/*xmlhttp.open("GET", url);
			xmlhttp.onreadystatechange=executaFuncao;
			xmlhttp.send(null);*/
		} else if (window.ActiveXObject) {
			var xmlHttpVersions = new Array("MSXML2.XMLHTTP.7.0",
																			"MSXML2.XMLHTTP.6.0",
																			"MSXML2.XMLHTTP.5.0",
																			"MSXML2.XMLHTTP.4.0",
																			"MSXML2.XMLHTTP.3.0",
																			"MSXML2.XMLHTTP",
																			"Microsoft.XMLHTTP");
			for (var i = 0; i < xmlHttpVersions.length && !xmlhttp; i++) {
				try {
					xmlhttp = new ActiveXObject(xmlHttpVersions[i]);
				}
				catch(e) {}
			}
			/*if (xmlhttp) {
				xmlhttp.open("GET", url);
				xmlhttp.onreadystatechange=executaFuncao;
				xmlhttp.send(); 
			}*/
		}
	}
	cache.push(url);
	cache.push(f);
	mostraFeedBack();
	setTimeout("processaCache();", 500);
}

function processaCache() {
	if (xmlhttp) {
		if ((xmlhttp.readyState==0 || xmlhttp.readyState==4) && cache.length>0) {
			cacheUrl = cache.shift();
			func = cache.shift();
			xmlhttp.open("GET", cacheUrl, true);
			xmlhttp.onreadystatechange=executaFuncao;
			xmlhttp.send(null); 
		}
	}
	if (cache.length<1)
		ocultaFeedBack();
}


/****************************************************************************************
* FUNÇÃO QUE CHAMA A FUNÇÃO DESEJADA PARA A AÇÃO
* ------------------------------------------------------------------
* É chamada pela function loadXMLDoc();
* Verifica qual o valor da variável func e chama a função específica
*/

function leftZero() {}

function executaFuncao(){
	if (func == -1) {
	  // não tem tratamento
	} else if	(func == 0){
		getCidades();
	} else if (func==1) {
	  validaSenha();		
	} else if (func==2) {
	  boolExec = false;	
	  fnEmailExiste();
	} else if (func==3) {
	  boolExec = false;	
	  fnDocExiste();
	} else if (func==4) {
		carregarPedido();	
	} else if (func==5) {
		atualizaValorPedido();	
	} else if (func==6) {
		mostraProdutoDetalhe();	
	}
	
	setTimeout("processaCache();", 500);
}
/* FIM DA FUNÇÃO executaFuncao() */

function updateTotalDestinatario(){
	if (xmlhttp.readyState == 4) {
		if (xmlhttp.status == 200) {
			document.getElementById("destinatariosSelecionados").innerHTML = xmlhttp.responseText;
		}else{
			alert("Houve um problema ao obter os dados:\n" + xmlhttp.statusText);
		}
	}
}

function detalhesBannerTipo() {
  var xmlCidade;
	if (xmlhttp.readyState == 4) {
		if (xmlhttp.status == 200) {
      xmlTipoBanner = xmlhttp.responseXML.documentElement;
			var altura 							= xmlTipoBanner.getElementsByTagName('altura');
			var largura 						= xmlTipoBanner.getElementsByTagName('largura');			
			var formatosArquivo 		= xmlTipoBanner.getElementsByTagName('formatosArquivo');			
			if (largura.item(0)) {
				document.getElementById("detalhesBannerTipo").innerHTML = "Largura: " +
					largura.item(0).attributes.getNamedItem("value").value + " - Altura: " +			
					altura.item(0).attributes.getNamedItem("value").value + " - Arquivos: " +
					formatosArquivo.item(0).attributes.getNamedItem("value").value;
				document.getElementById("formatosArquivo").value = 
					formatosArquivo.item(0).attributes.getNamedItem("value").value;
			}
			else {
				document.getElementById("detalhesBannerTipo").innerHTML = "";
				document.getElementById("formatosArquivo").value = "";			
			}			
    }
  }
}


function fnEmailExiste() {
	var msgErroEmail = document.getElementById('msgErroEmail');	
	if (xmlhttp.readyState == 4) {
		if (xmlhttp.status == 200) {
			if (xmlhttp.responseText=="0") {
				document.getElementById('btEmailValido').value = 0;
	//			msgErroEmail.innerHTML = "Já existe esse e-mail cadastrado em nosso sistema. Por favor, verifique!";
	//			msgErroEmail.style.display='';
			}else{
				document.getElementById('btEmailValido').value = 1;
				msgErroEmail.style.display='none';
			}
		}
	}
}

function fnDocExiste() {
	var msgErroCPF = document.getElementById('msgErroCPF');	
	if (xmlhttp.readyState == 4) {
		if (xmlhttp.status == 200) {
			if (xmlhttp.responseText=="0") {
				document.getElementById('btDocValido').value = 0;
				
			}else{
				document.getElementById('btDocValido').value = 1;
				msgErroCPF.style.display='none';
			}
			var form = document.getElementById('form1');
			if (validaCadastro(form)==true)
			{
				form.submit();	
			}
		}
	}
}



function saiuConsulta() {
	if (xmlhttp.readyState == 4) {
		if (xmlhttp.status == 200) {
			top.close();
		}
	}
}

function verificaMensagemChat() {
	if (xmlhttp.readyState == 4) {
		if (xmlhttp.status == 200) {
			if (xmlhttp.responseText=="1") {
				top.frames[1].location = top.frames[1].location;
				top.frames[2].location = top.frames[2].location;				
			}
		}
	}
}

function saiuChat() {
	if (xmlhttp.readyState == 4) {
		if (xmlhttp.status == 200) {
			top.close();
		}
	}
}

function alteraTamanhoFonteChat() {
	if (xmlhttp.readyState == 4) {
		if (xmlhttp.status == 200) {
		 	top.frames[1].location = top.frames[1].location;
		}
	}
}


/****************************************************************************************
* FUNÇÃO PARA RECUPERAR AS CIDADES DO ESTADO ESCOLHIDO
* -------------------------------------------------------------------------------
* Função que recupera todas as cidades do estado escolhido
* -------------------------------------------------------------------------------
* Faz uma consulta no banco procurando as cidades pelo id do estado escolhido.
*/

function validaSenha(){
	if (xmlhttp.readyState == 4) {
		if (xmlhttp.status == 200) {
		  alert(xmlhttp.responseText);
		  document.getElementById('validou').value = xmlhttp.responseText;
	  }
	}
}

function getCidades() {
  var xmlCidade;
  var spnidCidade = document.getElementById('spnidCidade');
  spnidCidade.innerHTML = 'Aguarde...';
	if (xmlhttp.readyState == 4) {
		if (xmlhttp.status == 200) {
      xmlCidade = xmlhttp.responseXML.documentElement;
			var idCidade 		= xmlCidade.getElementsByTagName('idCidade');
			var idCidadeSelecionada = xmlCidade.getElementsByTagName('idCidadeSelecionada');
			var nomeCidade 	= xmlCidade.getElementsByTagName('nomeCidade');
			
			var sinnerHTML 	= "<select id=\"idCidade\"  class=\"bordas\" style=\"width: 100%\" onChange=\"document.form1.idCidadeAux.value = this.value;\">";
			sinnerHTML += "<option value=\"0\">Selecione</option>";
			for (var i=0; i<idCidade.length; i++) {
				if (idCidadeSelecionada.item(0).attributes.getNamedItem('value').value==idCidade.item(i).attributes.getNamedItem('value').value) {
 				  sinnerHTML += "<option value=\"" + idCidade.item(i).attributes.getNamedItem('value').value +"\" selected>"+
				    nomeCidade.item(i).attributes.getNamedItem('value').value +"</option>";
				}
				else {
 				  sinnerHTML += "<option value=\"" + idCidade.item(i).attributes.getNamedItem('value').value +"\">"+
				    nomeCidade.item(i).attributes.getNamedItem('value').value +"</option>";
				}
		  }
		  sinnerHTML += "</select>";
		  spnidCidade.innerHTML = sinnerHTML;
    }
  }
}

function buscaProdutoSubGrupo () {
  var spnSubGrupo = document.getElementById('spnSubGrupo');
	if (xmlhttp.readyState == 4) {
		if (xmlhttp.status == 200) {
		  spnSubGrupo.innerHTML = xmlhttp.responseText;
		}
	}
}

function buscaEmailSpn() {
  var spnEmail = document.getElementById('spnEmail');
	if (xmlhttp.readyState == 4) {
		if (xmlhttp.status == 200) {
		  spnEmail.innerHTML = xmlhttp.responseText;
		}
	}
}

function carregarModelos() {
  var divModelos = document.getElementById('divModelos');
	if (xmlhttp.readyState == 4) {
		if (xmlhttp.status == 200) {
		  divModelos.innerHTML = xmlhttp.responseText;
		}
	}
}

function carregarPedido() {
  var divPedidoDados = document.getElementById('divPedidoDados');
	if (xmlhttp.readyState == 4) {
		if (xmlhttp.status == 200) {
		  divPedidoDados.innerHTML = xmlhttp.responseText;
		}
	}
}

function atualizaValorPedido() {
  var divPedidoDados = document.getElementById('valorAtualizado');
	if (xmlhttp.readyState == 4) {
		if (xmlhttp.status == 200) {
		  divPedidoDados.innerHTML = xmlhttp.responseText;
		}
	}
}

function mostraProdutoDetalhe(){
  var divPedidoDados = document.getElementById('produtoDetalhe');
	if (xmlhttp.readyState == 4) {
		if (xmlhttp.status == 200) {
		  divPedidoDados.innerHTML = xmlhttp.responseText;
		}
	}
}

