var msgAguarde = "<h2>Aguarde</h2> <div id=\"boxDetProd\"><p><img src=\"imagem/img_loading.gif\" alt=\"carregando\" /></p></div>";

function MostraEsconde(sId) {
	var sDiv=document.getElementById(sId);
	if (sDiv.style.display=="") {
		sDiv.style.display="none";
	} else {
		sDiv.style.display="";
	}
}

function TelefoneFormat(Campo, e) { 
	var key = ''; 
	var len = 0; 
	var strCheck = '0123456789'; 
	var aux = ''; 
	var whichCode = (window.Event) ? e.which : e.keyCode; 

	if (whichCode == 13 || whichCode == 8 || whichCode == 0) { 
		return true;  // Enter backspace ou FN qualquer um que não seja alfa numerico 
	}
	
    key = String.fromCharCode(whichCode); 
	if (strCheck.indexOf(key) == -1){ 
		return false;  //NÃO E VALIDO 
	} 
     
    aux = Telefone_Remove_Format(Campo.value); 
     
    len = aux.length; 
    if(len>=10) 
    { 
        return false;    //impede de digitar um telefone maior que 10 
    } 
    aux += key; 
     
    Campo.value = Telefone_Mont_Format(aux); 
    return false; 
} 

function  Telefone_Mont_Format(Telefone) { 
    var aux = len = ''; 
     
    len = Telefone.length; 
    if(len<=9) 
    { 
        tmp = 5; 
    } 
    else 
    { 
        tmp = 6; 
    } 
     
    aux = ''; 
    for(i = 0; i < len; i++) 
    { 
        if(i==0) 
        { 
            aux = '('; 
        } 
        aux += Telefone.charAt(i); 
        if(i+1==2) 
        { 
            aux += ')'; 
        } 
         
        if(i+1==tmp) 
        { 
            aux += '-'; 
        } 
    } 
    return aux ; 
} 

function  Telefone_Remove_Format(Telefone) { 
    var strCheck = '0123456789'; 
    var len = i = aux = ''; 
    len = Telefone.length; 
    for (i = 0; i < len; i++) { 
        if (strCheck.indexOf(Telefone.charAt(i))!=-1) { 
            aux += Telefone.charAt(i); 
        } 
    } 
    return aux; 
} 

function autocompletacep(cep) {

	var r = $.ajax({url: "http://www.compreautomacao.com.br/automacao/cep.asp?cep=" + cep, async: false, cache: true}).responseText;
	var json = eval("(" + r + ")");
	
	try {
		document.getElementById("tEndereco").value = json["cep"]["endereco"];
		document.getElementById("tBairro").value = json["cep"]["bairro"];
		document.getElementById("tCidade").value = json["cep"]["cidade"];
		
		for(i=0;i<document.getElementById("tEstado").length;i++) {
			if(document.getElementById("tEstado").options[i].value==json["cep"]["estado"]) {
				document.getElementById("tEstado").selectedIndex=i;
			}
		}
		
	} catch (e) {
	
	}

}


function getValor(Elemento) {
   return document.getElementById(Elemento).value;
}

	
//Função para ocultar a janela que
//avisa que o produto foi comprado
function oculta() {
		clearInterval(intInterval);
		$('#adicionou').fadeOut('slow');
		void(0);
}

function ItemProduto2(Produto,Preco,Quantidade,TipoConexao,Pagina) {

		var Prod = Produto;
		var Pre = Preco;
		var Qtd = getValor(Quantidade);
		var Pag = Pagina;
		var TpConexao = getValor(TipoConexao);        

		//essencial para o redirecionamento da página após a compra =)
		Pag=Pag.replace(/[&]+/g,"%26").replace(/[?]+/g,"%3F");

		getPage('Evento.asp',"evento=CompraProduto&produto=" + Prod + "&preco=" + Pre + "&quantidade=" + Qtd + "&tipoconexao=" + TpConexao + "&pagina=" + Pag,'retorno');
		window.document.getElementById('bgRetorno').style.backgroundImage = 'url("Imagem/bgConteudo2.gif")';
		window.document.getElementById('retorno').style.backgroundImage = 'url("Imagem/rodape_retorno2.jpg")';
		//var r = $.ajax({url: "Evento.asp?evento=CompraProduto&produto=" + Prod + "&preco=" + Pre + "&quantidade=" + Qtd + "&pagina=" + Pag, async: false, cache: false}).responseText;

}



function ItemProduto(Produto,Preco,Quantidade,Pagina) {

		var Prod = Produto;
		var Pre = Preco;
		var Qtd = getValor(Quantidade);
		var Pag = Pagina;
		
		$("#adicionou").fadeIn("slow");
		
		//essencial para o redirecionamento da página após a compra =)
		Pag=Pag.replace(/[&]+/g,"%26").replace(/[?]+/g,"%3F");
		
		var r = $.ajax({url: "Evento.asp?evento=CompraProduto&produto=" + Prod + "&preco=" + Pre + "&quantidade=" + Qtd + "&pagina=" + Pag, async: false, cache: false}).responseText;
		
		if ($.browser.msie) {
			if (parseInt($.browser.version)<=6) {
				efeito = false;
			} else {
				efeito = true;
			}
		} else {
			efeito = true;
		}

//		var htmlComprou = "<span style=\"display: block; position: relative;\"><strong>Produto adicionado ao carrinho</strong><br /> <a href=\"javascript:makeHistory('retorno:carrinho.asp');\"><strong>Ver carrinho</strong></a> | <a href=\"javascript:makeHistory('retorno:carrinho.asp');\">Fechar a compra</a> | <a href=\"javascript:getPage('lista.asp','"+ Pag.replace("%26","&").replace("%3F","").replace("lista.asp","") +"','retorno');\">Continuar comprando</a></span>";
		var htmlComprou = "<span style=\"display: block; text-align: center; position: relative;\"><strong>Produto adicionado ao carrinho</strong><br /> <a href=\"carrinho.asp\"><strong>Ver carrinho</strong></a> | <a href=\"carrinho.asp\">Fechar a compra</a></span>";

		if (efeito) {
			$("#tblProdFX" + Produto).animate({ 
			                                  opacity: 0.1
			                                  }, 1000, function () {
				                                  document.getElementById("tblProdFX" + Produto).innerHTML = htmlComprou;
				                                  $("#tblProdFX" + Produto).animate({opacity:1},1000);
			                                  });
      	} else {
			document.getElementById("tblProdFX" + Produto).innerHTML = htmlComprou;
      	}
		intInterval = setInterval(oculta,5000);
}

function AtualizaProduto(Produto,Preco,Quantidade,Pagina) {
	var Prod = Produto;
	var Pre = Preco;
	var Qtd = getValor(Quantidade);
	var Pag = Pagina;
	getPage('Evento.asp','evento=AtualizarProduto&produto='+Prod+'&preco='+Pre+'&quantidade='+Qtd+'&pagina='+Pag,'retorno');
}

function ExcluiItemPedido(Produto,Pagina) {
	var Prod = Produto;
	var Pag = Pagina;
	var r = $.ajax({url: "Evento.asp?evento=ExcluirProdutoCarrinho&produto=" + Prod + "&pagina=" + Pag, async: false, cache: false}).responseText;

	$("#produto_" + Produto).animate({ 
	                                  opacity: 0
	                                  }, 1000, function () {
		                                  getPage("carrinho.asp","","retorno");
	                                  });

	//$("#produto_" + Produto).fadeOut("slow");
}

function MinimaQtd(Objeto) {
	var x = getValor(Objeto);
	if (x < 1){ document.forms[0].elements[Objeto].value = "1"; }
}

function MaximaQtd(Objeto) {
	var x = getValor(Objeto);
	if (x > 99){ document.forms[0].elements[Objeto].value = "99"; }
}


function Tecla(evt) {
	 var charCode = (evt.which) ? evt.which : event.keyCode
	 if (charCode > 31 && (charCode < 48 || charCode > 57)) {
		return false;
	 } else {
	 return true;
	 }
}

function cadastro(frm) {
	var tipoCliente = frm.tipoCliente.value;
	var evento = jQuery.trim(frm.evento.value);
	var txtcodigo = jQuery.trim(frm.txtcodigo.value);
	var txtdescricao = jQuery.trim(frm.txtdescricao.value);
	var txtcnpj = jQuery.trim(frm.txtcnpj.value);
	var txtinscricao = jQuery.trim(frm.txtinscricao.value);
	var txtendereco = frm.txtendereco.value;
	var txtbairro = frm.txtbairro.value;
	var txtcidade = frm.txtcidade.value;
	var txtestado = frm.txtestado.value;
	var txtpais = frm.txtpais.value;
	var txtcep = frm.txtcep.value;
	var txtemail = frm.txtemail.value;
	var txtsenha = frm.txtsenha.value;
	var txtsenha2 = frm.txtsenha2.value;
	var txtresponsavel = jQuery.trim(frm.txtresponsavel.value);
	var txttelefone = frm.txttelefone.value;
	var txtnumero = frm.txtnumero.value;
	var txtcomplemento = frm.txtcomplemento.value;

	if (txtdescricao=="") {
		if (tipoCliente==0) {
			window.alert("Preencha o campo com a razão social");
		} else {
			window.alert("Preencha seu nome");
		}
		frm.txtdescricao.focus();
	} else if (txtresponsavel=="") {
		window.alert("Preencha o nome do responsável pelas compras na loja");
		frm.txtresponsavel.focus();
	} else if(txtcnpj=="") {
		if (tipoCliente==0) {
			window.alert("Digite o CNPJ");
		} else {
			window.alert("Digite seu CPF");
		}
		frm.txtcnpj.focus();
	} else if(txtinscricao=="") {
		if (tipoCliente==0) {
			window.alert("Digite a inscrição estadual.");
		} else {
			window.alert("O campo RG precisa ser preenchido.");
		}
		frm.txtinscricao.focus();
	} else if(txtendereco=="" || txtbairro=="" || txtcidade=="") {
		if (tipoCliente==0) {
			window.alert("Digite o endereço completo da empresa");
		} else {
			window.alert("É necessário informar seu endereço completo");
		}
		frm.txtendereco.focus();
	} else if(txtcep=="")	{
		window.alert("Digite o CEP corretamente");
		frm.txtcep.focus();
	} else if(txttelefone=="") {
		window.alert("Digite o telefone");
		frm.txttelefone.focus();
	} else if(txtnumero=="") {
		window.alert("Digite o numero");
		frm.txtnumero.focus();
	} else if (txtemail=="") {
		window.alert("Digite um e-mail para acessar a loja");
		frm.txtemail.focus();
	} else if (txtsenha=="" || txtsenha.length<6) {
		window.alert("Crie uma senha com pelo menos 6 dígitos");
		frm.txtsenha.focus();
	} else if (txtsenha!=txtsenha2) {
		window.alert("A senha não confere com a confirmação");
		frm.txtsenha.focus();
	} else {
		
		getPage('Evento.asp','evento=ClienteIncluir&tipoCliente=' + tipoCliente + '&Codigo='+txtcodigo+'&Descricao='+txtdescricao+'&Cnpj='+txtcnpj+'&InscricaoEstadual='+txtinscricao+'&Endereco='+txtendereco+'&Bairro='+txtbairro+'&Cidade='+txtcidade+'&Estado='+txtestado+'&Pais='+txtpais+'&Cep='+txtcep+'&Telefone='+txttelefone+'&Email='+txtemail+'&Senha='+txtsenha+'&Responsavel='+txtresponsavel+'&Numero='+txtnumero+'&Complemento='+txtcomplemento,'retorno');
		
		//urlget = 'Evento.asp?evento=ClienteIncluir&tipoCliente=' + tipoCliente + '&Codigo='+txtcodigo+'&Descricao='+txtdescricao+'&Cnpj='+txtcnpj+'&InscricaoEstadual='+txtinscricao+'&Endereco='+txtendereco+'&Bairro='+txtbairro+'&Cidade='+txtcidade+'&Estado='+txtestado+'&Pais='+txtpais+'&Cep='+txtcep+'&Telefone='+txttelefone+'&Email='+txtemail+'&Senha='+txtsenha+'&Responsavel='+txtresponsavel+'&ResponsavelCelular='+txtrcelular+'&ResponsavelEmail='+txtremail+'&Msn='+txtmsn+'&Skype='+txtskype+'&Banco='+txtbbanco+'&Agencia='+txtbagencia+'&ContaCorrente='+txtbconta+'&Gerente='+txtbgerente+'&GerenteTelefone='+txtbtelefone+"&GerenteRamal="+txtbramal
		
		//document.location=urlget;

	}
}

function lembraSenha(email) {
	if (email=="" || email==null) {
		window.alert("Digite o e-mail corretamente.");
	} else {
		var r = $.ajax({url: "evento.asp?evento=lembraSenha&email=" + email, async: false, cache: false}).responseText;
		if (r=="ok") {
			window.alert("Seus dados de acesso foram enviados para seu e-mail.");
		} else {
			window.alert("Seu e-mail nao esta cadastrado em nosso banco de dados.");
		}
	}
}

function encontrouProduto(email, telefone, produto) {
	if (email=="" || email==null || telefone=="" || telefone==null || produto=="" || produto==null) {
		window.alert("Todos os campos sao obrigatorios. Por favor, preencha-os.");
	} else {
		var r = $.ajax({url: "evento.asp?evento=encontrouproduto&email=" + email + "&telefone=" + telefone + "&pedidossite=" + produto, async: false, cache: false}).responseText;
		if (r=="ok") {
			window.alert("Seu pedido foi enviado com sucesso. Breve entraremos em contato.");
		} else {
			window.alert("Infelizmente nao foi possivel o envio desta mensagem. Contate-nos para resolucao do problema.");
		}
	}
}

function enviarContato(objFRM) {
	var txtNome = objFRM.txtNome.value;
	var txtEmail = objFRM.txtEmail.value;
	var txtAssunto = objFRM.txtAssunto.value;
	var txtMsg = objFRM.txtMsg.value;

	getPage('enviaEmail.asp','txtNome='+txtNome+'&txtEmail='+txtEmail+'&txtAssunto='+txtAssunto+'&txtMsg='+txtMsg,'retorno')
}

function getPage(Page, Parametros, Elemento) {
	Page = Page+'?'+Parametros;
	Pagin = Page;
	Elem = Elemento;

	document.getElementById(Elemento).innerHTML = msgAguarde;

	$.ajax({
		url: Page,
		cache: false,
		success: function(html){

			document.getElementById(Elem).innerHTML = html;
		}
	});


}

function getPage2(Page, Parametros, Elemento) {
	getPage(Page, Parametros, Elemento);
}

function echeck(str) {

	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	if (str.indexOf(at)==-1){
	   alert("E-mail Inválido")
	   
	   return false
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
	   alert("E-mail Inválido")
	   
	   return false
	}

	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		alert("E-mail Inválido")
		
		return false
	}

	 if (str.indexOf(at,(lat+1))!=-1){
		alert("E-mail Inválido")
		
		return false
	 }

	 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		alert("E-mail Inválido")
		
		return false
	 }

	 if (str.indexOf(dot,(lat+2))==-1){
		alert("E-mail Inválido")
		
		return false
	 }
	
	 if (str.indexOf(" ")!=-1){
		alert("E-mail Inválido")
		
		return false
	 }
	 return true
}

function ValidateForm(){
	var emailID=document.formEnviaMensagem.txtEmail
	
	if (window.document.getElementById('txtNome').value == ''||window.document.getElementById('txtEmail').value == ''||window.document.getElementById('txtAssunto').value == ''||window.document.getElementById('txtMensagem').value == '') {
		window.alert('Todos os campos são obrigatórios. Por favor, preencha-os!');
		document.formEnviaMensagem.action = 'index.asp#conteudo:contato.asp;bannerLateral:bannerpropaganda.asp';
	}
	if (echeck(emailID.value)==false){
		emailID.value=""
		emailID.focus()
		return false
	}
	return true
 }

