/*
INFORMAÇÕES IMPORTANTES

VALORES readystate:
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready

VALORES status
200: "OK"
404: Page not found
*/

var ajax;
var dados;

//INICIA AJAX
function requisicaoAjax(tipo, url, assinc, nomeFuncao)
{
	if (window.XMLHttpRequest) //FIREFOX, SAFARI
	{
		ajax = new XMLHttpRequest();
	}
	else if (window.ActiveXObject) //INTERNET EXPLORER
	{
		ajax = new ActiveXObject("Microsoft.XMLHTTP");
	}
	else
	{
		alert('Seu navegador não possui suporte para este site!');
	}
	
	if (ajax != null)
	{
		//ABRE A REQUISIÇÃO
		ajax.open(tipo, url, assinc);
		
		//FUNÇÃO QUE SERÁ CHAMADA NO RETORNO NO AJAX
		ajax.onreadystatechange = nomeFuncao;
		
		//INICIA O TRANSPORTE DE DADOS
		ajax.send(dados);
	}
}

//FUNÇÃO CALCULA FRETE
function ajaxCalculaFrete()
{
	if (ajax.readyState < 4)
	{
		document.getElementById("dadosFretePrazo").style.visibility = "collapse";
		document.getElementById("fretePrazoSpinner").innerHTML='&nbsp;<img src="images/ajaxSpinner.gif" />';
	}
	else if (ajax.readyState == 4)
	{
		document.getElementById("fretePrazoSpinner").innerHTML='';
		document.getElementById("dadosFretePrazo").style.visibility = "visible";
		
		if (ajax.status == 200)
		{
			//RESPOSTA DO SERVIDOR
			var texto = ajax.responseText;
			document.getElementById("fretePrazo").innerHTML=texto; 
			
			//ZERA VALOR DO FRETE
			var vProd  = document.form1.valorProdutos.value;
			var vFrete = "0,00";
			var vTotal = moeda2Float(vProd)+moeda2Float(vFrete);
			
			document.getElementById("valorFrete").innerHTML = vFrete;
			document.getElementById("valorPedido").innerHTML = float2Moeda(vTotal);
		}
		else
		{
			alert('Ocorreu um problema na comunicação XMLHTTPRequest');
		}
	}
}

//FUNÇÃO BUSCA DADOS DO CEP
function ajaxBuscaCep()
{
	if (ajax.readyState < 4)
	{
		document.getElementById("dadosCepSpinner").innerHTML='&nbsp;<img src="images/ajaxSpinner.gif" />';
	}
	else if (ajax.readyState == 4)
	{
		document.getElementById("dadosCepSpinner").innerHTML='';
		
		if (ajax.status == 200)
		{
			//RESPOSTA DO SERVIDOR
			var xml  = ajax.responseXML;
			var raiz = xml.documentElement;
			var nodos;
			
			if (raiz.hasChildNodes())
			{
				nodos = raiz.childNodes;
				
				for (c=0; c<nodos.length; c++)
				{
					if (nodos[c].hasChildNodes())
					{
						if (nodos[c].nodeName == "logradouro")
						{
							document.form1.endereco.value = nodos[c].firstChild.nodeValue;
						}
						else if (nodos[c].nodeName == "bairro")
						{
							document.form1.bairro.value = nodos[c].firstChild.nodeValue;
						}
						else if (nodos[c].nodeName == "cidade")
						{
							document.form1.cidade.value = nodos[c].firstChild.nodeValue;
						}
						else if (nodos[c].nodeName == "uf")
						{
							document.form1.estado.value = nodos[c].firstChild.nodeValue;
						}
					}
					else
					{
							document.form1.endereco.value = "";
							document.form1.numero.value = "";
							document.form1.bairro.value = "";
							document.form1.cidade.value = "";
							document.form1.estado.value = "";
					}
				}
			}
						 
		}
		else
		{
			alert('Ocorreu um problema na comunicação XMLHTTPRequest');
		}
	}
}

//FUNÇÃO VERIFICA EMAIL
function ajaxVerificaEmail()
{
	if (ajax.readyState < 4)
	{
		document.getElementById("verificaEmailSpinner").innerHTML='&nbsp;<img src="images/ajaxSpinner.gif" />';
	}
	else if (ajax.readyState == 4)
	{
		document.getElementById("verificaEmailSpinner").innerHTML='';
		
		if (ajax.status == 200)
		{
			//RESPOSTA DO SERVIDOR
			var texto = ajax.responseText;
			
			if (texto != "")
			{
				document.getElementById("verificaEmailSpinner").innerHTML=texto;
				document.form1.email.value = "";
				document.form1.email.focus();
			}
		}
		else
		{
			alert('Ocorreu um problema na comunicação XMLHTTPRequest');
		}
	}
}

//ADICIONAR PRODUTO AO CARRINHO DE COMPRAS - AJAX
function ajaxAdicionar(produto, disponivel)
{
	if (disponivel == "S")
	{
		var url   = "lib/ajaxAdCarrinho.php?produto="+produto;
		requisicaoAjax("GET", url, true, ajaxAdCarrinho);
	}
	else
	{
		alert('Produto indisponível no momento!');
	}
}

//FUNÇÃO ADICIONA PRODUTO AO CARRINHO
function ajaxAdCarrinho()
{
	if (ajax.readyState == 4)
	{
		if (ajax.status == 200)
		{
			//RESPOSTA DO SERVIDOR
			var xml  = ajax.responseXML;
			var raiz = xml.documentElement;
			var nodos;
			
			if (raiz.hasChildNodes())
			{
				nodos = raiz.childNodes;
				
				for (c=0; c<nodos.length; c++)
				{
					if (nodos[c].hasChildNodes())
					{
						if (nodos[c].nodeName == "msgAlerta")
						{
							alert(nodos[c].firstChild.nodeValue);
						}
						else if (nodos[c].nodeName == "qtdeProduto")
						{
							document.getElementById("nItensCarrinho").innerHTML = nodos[c].firstChild.nodeValue;
						}
					}
				}
			}
						 
		}
		else
		{
			alert('Ocorreu um problema na comunicação XMLHTTPRequest');
		}
	}
}

//FUNÇÃO VERIFICA SUBCATEGORIAS
function ajaxVerificaSubcategorias()
{
	if (ajax.readyState < 4)
	{
		document.getElementById("verificaSubcategoriaSpinner").innerHTML='&nbsp;<img src="../images/ajaxSpinner.gif" />';
	}
	else if (ajax.readyState == 4)
	{
		document.getElementById("verificaSubcategoriaSpinner").innerHTML='';
		
		if (ajax.status == 200)
		{
			//RESPOSTA DO SERVIDOR
			var xml = ajax.responseXML;
			
			//TAG SUBCATEGORIA
			var arraySubcategoria = xml.getElementsByTagName("subcategoria");
			
			//REMOVE OPÇÕES ANTERIORES DO SELECT DE SUBCATEGORIAS
			qtdeOpcoes = document.forms[0].subcategoriaProduto.length;
			for (s=qtdeOpcoes-1; s>0; s--)
			{
				document.forms[0].subcategoriaProduto.options.remove(s);
			}
	
			//ELEMENTOS DENTRO DA TAG SUBCATEGORIA
			if (arraySubcategoria.length > 0)
			{				
				//ENVIA DADOS PARA O SELECT DE SUBCATEGORIAS
				document.getElementById("opcao").innerHTML = "Selecione...";
				
				for(var i=0; i<arraySubcategoria.length; i++)
				{
					var item = arraySubcategoria[i];
					var idSubcategoria   = item.getElementsByTagName("id")[0].firstChild.nodeValue;
					var nomeSubcategoria = item.getElementsByTagName("nome")[0].firstChild.nodeValue;
					
					//CRIA OPTION
					var novaSubcategoria   = document.createElement("option");
					//ATRIBUI UM ID A ESTE OPTION
					novaSubcategoria.setAttribute("id", "opcao");
					//ATRIBUI UM VALOR A ESTE OPTION
					novaSubcategoria.value = idSubcategoria;
					//ATRIBUI UM TEXT0 A ESTE OPTION
					novaSubcategoria.text  = nomeSubcategoria;
					//CRIA NOVO ELEMENTO
					document.forms[0].subcategoriaProduto.options.add(novaSubcategoria);
				}
				document.forms[0].possuiSubcategoria.value = "S";
				document.getElementById("subcategoriaDivisao").style.visibility = "visible";
				document.getElementById("subcategoriaTitulo").style.visibility  = "visible";
				document.getElementById("subcategoriaCampo").style.visibility   = "visible";
			}
			else
			{			
				document.forms[0].possuiSubcategoria.value = "N";
				document.getElementById("subcategoriaDivisao").style.visibility = "collapse";
				document.getElementById("subcategoriaTitulo").style.visibility  = "collapse";
				document.getElementById("subcategoriaCampo").style.visibility   = "collapse";
			}
		}
		else
		{
			alert('Ocorreu um problema na comunicação XMLHTTPRequest');
		}
	}
}
