function scrollToAnchor(anchorName){
   //set the hash so people can bookmark
   window.location.hash = anchorName;
   //scroll the anchor into view
   document.getElementsByName(anchorName)[0].scrollIntoView(true);
 }

function insereNewsletter(url) {
	var count = 0;
	
	if (!$('email').value || !validaEmail($('email').value))	{ count = count + 1; }
	
	if (count > 0) {
    alert('E-mail inválido.');
    return false;
  }
	 
	var php = url+"?on=capa&in=ajax&ac=newsletter";

	var parametros = 'nome='+$('nome').value+'&email='+$('email').value;
	var ajaxNews = new Ajax.Request(php,
                                    {
                                            method: 'post',
                                            parameters: parametros,
                                            onComplete: function newsReturn(retorno) {
                                                  var resposta = retorno.responseText;
                                                  $('resultNewsletter').innerHTML = resposta;
                                                  $('nome').value = "";
                                                  $('email').value = "";
                                     }
                                    });

}
function removeNewsletter(url) {
	var count = 0;
	
	if (!$('email').value || !validaEmail($('email').value))	{ count = count + 1; }
	
	if (count > 0) {
    alert('E-mail inválido.');
    return false;
  }
	 
	var php = url+"?on=capa&in=ajax&ac=newsletterRemover";

	var parametros = 'nome='+$('nome').value+'&email='+$('email').value;
	var ajaxNews = new Ajax.Request(php,
                  {
                          method: 'post',
                          parameters: parametros,
                          onComplete: function newsReturn(retorno) {
                                      var resposta = retorno.responseText; 
                                      $('resultNewsletter').innerHTML = resposta;
                                      $('nome').value = "";
                                      $('email').value = "";
                  }
                  });
}


function carregaCep(url,valor) {
         if(valor.length >= 9) {
                  $('carregandoCep').innerHTML = 'Carregando ...';
                  
                  var php = url+"cadastro/ajax/carregaCep";
                  var parametros = 'cep='+valor;
                  var ajaxNews = new Ajax.Request(php,
                                    {
                                             method: 'post',
                                             parameters: parametros,
                                             onComplete: function retornoCarregaCep(retorno) {
                                                      cepXML	= retorno.responseXML;
                                                      ceps	= cepXML.getElementsByTagName( 'cep' );
                                                      
                                                      estado 	= ceps[0].getElementsByTagName( 'estado' );
                                                      estado 	= estado[0].firstChild.nodeValue;
                                                      cidade 	= ceps[0].getElementsByTagName( 'cidade' );
                                                      cidade 	= cidade[0].firstChild.nodeValue;
                                                      rua 	= ceps[0].getElementsByTagName( 'nome' );
                                                      rua 	= rua[0].firstChild.nodeValue;
                                                      tipo 	= ceps[0].getElementsByTagName( 'tipo' );
                                                      tipo	= tipo[0].firstChild.nodeValue;
                                                      bairroIni	= ceps[0].getElementsByTagName( 'bairroIni' );
                                                      bairroIni	= bairroIni[0].firstChild.nodeValue;
                                                      
                                                      if(estado != 0)            {
                                                               $('estado').value = estado;
                                                               $('pais').value = 'Brasil';
                                                      }
                                                      if(cidade != 0)            $('cidade').value = cidade;
                                                      if(rua != 0)               $('endereco').value = rua;
                                                      if(bairroIni != 0)         $('bairro').value = bairroIni;
                                                      $('carregandoCep').innerHTML = '';
                                             }
                                    });
         }
}
//----------------------------------------------------------
function changeImage(obj,src) {
   $(obj).src = src;
   return false;
}//----------------------------------------------------------
function limpaCarrinho(url) {
         if (confirm('Deseja limpar o carrinho?'))
                   window.location = url+'?on=carrinho&in=excluirCarrinho';
}
//----------------------------------------------------------
function removeItem(url,id) {
   if (confirm('Deseja excluir esse item?')) {
    
      ajaxRedirect(url+'?on=carrinho&in=excluirProduto&id='+id,'',url+'?on=carrinho');
            
    }
   
}
//----------------------------------------------------------
function addCarrinho(url,id) {
	 if ($('quantidade_'+id).value <= 0)  $('quantidade_'+id).value=1; 

	 ajaxFuncaoCarrinho(url+'?on=carrinho&in=ajax&ac=adicionarProduto&produto_id='+id+'&quantidade='+$('quantidade_'+id).value,'','preco_total_'+id);
}
//----------------------------------------------------------
function getValorParcela(url,id) {
	
	if ($('parcela').value > 0 && $('parcela').value <= 6) { 
		ajaxFuncao(url+'produtos/ajax/parcelas/'+id,'parcelas='+$('parcela').value,'div_parcela'); 
	} else {
		//alert('Valor inválido.'); 
		$('parcela').value='6';
		ajaxFuncao(url+'produtos/ajax/parcelas/'+id,'parcelas='+$('parcela').value,'div_parcela'); 
	}
}
//----------------------------------------------------------
var indiceNav = 0;

function getNavProduto(dir,url) {
	indice = dir == 'L' ? indiceNav-1 : indiceNav+1;
	
	if(indice >= 0 && indice < 12) {
		indiceNav = indice;
		getProdutoHome(url,produto[indiceNav]);
	}		
	
}
//----------------------------------------------------------
function getProdutoHome(url,id){

	for(i = 0; i <= 11; i++) { if(produto[i] == id) { indiceNav = i; break; } }
	
	var php 	   	= url + "capa/ajax/produtos";
	var parametros 	= 'produto_id='+ id;
	var ajaxNews 	= new Ajax.Request(php,{
												method: 'post',
												parameters: parametros,
												onComplete: retornoProdutoHome }); 
}
//----------------------------------------------------------
function retornoProdutoHome(retorno) {
	resposta  = retorno.responseXML;
	prod	  = resposta.getElementsByTagName('produto');
       
 	for( i = 0; i < prod.length; i++ ) {
       id			= prod[i].getElementsByTagName('id');
       id 			= id[0].firstChild.nodeValue;
   	   nome			= prod[i].getElementsByTagName('item');
       nome			= nome[0].firstChild.nodeValue;
       nome			= nome == '0' ? '' : nome;
       
       material		= prod[i].getElementsByTagName('material');
       material 	= material[0].firstChild.nodeValue;
       material		= material == '0' ? '' : ' - '+material;
       
       descricao	= prod[i].getElementsByTagName('descricao');
       descricao 	= descricao[0].firstChild.nodeValue;
       descricao	= descricao == '0' ? '' : descricao;
       
       preco		= prod[i].getElementsByTagName('preco');
       preco 		= preco[0].firstChild.nodeValue;
       
       precox		= prod[i].getElementsByTagName('precox');
       precox 		= precox[0].firstChild.nodeValue;
       
       foto			= prod[i].getElementsByTagName('foto');
       foto 		= foto[0].firstChild.nodeValue; 
  	}
   	
   	// MONTA OS DADOS DO PRODUTO NA PRINCIPAL					    	
   	$('destaqueIMG').innerHTML = ' <a href="produtos-visualizar-detalhe-'+id+'"> <img src="'+foto+'" alt="'+nome+'" title="'+nome+'" /> </a> ';
	$('destaqueNOME').innerHTML 		= nome+material;
	$('destaqueDESCRICAO').innerHTML 	= descricao;
	$('destaquePRECO').innerHTML 		= 'R$ '+preco;
	$('destaqueLINK').innerHTML 		= '<a href="produtos-visualizar-detalhe-'+id+'">[ + ] Veja Mais</a> &nbsp; ';
	$('destaquePRECOX').innerHTML 		= precox;
}

//----------------------------------------------------------
function enviaContato(form) {
	var count = 0;

	var erro = ' Preencha corretamente os campos abaixo:\n\n';
	
	if (!$F('nome'))								{ count = count + 1; erro = erro + '- Nome\n'; }
	if (!$F('email') || !validaEmail($F('email')))	{ count = count + 1; erro = erro + '- E-mail\n'; }
	if (!$F('telefone'))							{ count = count + 1; erro = erro + '- Telefone\n'; }
	if (!$F('mensagem'))							{ count = count + 1; erro = erro + '- Mensagem\n'; }
	
	if (count > 0)
  		alert(erro);
	else
  	  	$(form).submit();
	
}

//----------------------------------------------------------
function enviaCadastro(form,tipo_cadastro) {
	var count = 0;

	if (tipo_cadastro == 'PF') {
		var erro = '             - FORMULÁRIO DE CLIENTE - \n\nPreencha corretamente os campos abaixo:\n\n';

		if (!$F('nome'))								{ count = count + 1; erro = erro + '- Nome\n'; }
		if (!$F('sobrenome'))							{ count = count + 1; erro = erro + '- Sobrenome\n'; }
		if (!$F('cpf'))									{ count = count + 1; erro = erro + '- CPF\n'; }
		if (!checkCPFCNPJ('cpf','cpf'))									{ count = count + 1; erro = erro + '- CPF Inválido\n'; }
		
		if (!$F('data_nascimento'))						{ count = count + 1; erro = erro + '- Data de Nascimento\n'; }
		if (!$F('sexo'))								{ count = count + 1; erro = erro + '- Sexo\n'; }
		if (!$F('email') || !validaEmail($F('email')))	{ count = count + 1; erro = erro + '- E-mail\n'; }
		if (!$F('senha'))								{ count = count + 1; erro = erro + '- Senha\n'; }
		if (!$F('senha2'))								{ count = count + 1; erro = erro + '- Confirmação de Senha\n'; }
		if ($('senha').value != $('senha2').value)                { count = count + 1; erro = erro + '- As senhas não conferem.\n'; }
	}
	else {
		
		var erro = '             - FORMULÁRIO DE LOJISTA - \n\nPreencha corretamente os campos abaixo:\n\n';

		if (!$F('razao_social'))						{ count = count + 1; erro = erro + '- Razão Social\n'; }
		if (!$F('contato'))								{ count = count + 1; erro = erro + '- Nome de Contato\n'; }
		if (!$F('cnpj'))								{ count = count + 1; erro = erro + '- CNPJ\n'; }
		if (!checkCPFCNPJ('cnpj','cnpj'))									{ count = count + 1; erro = erro + '- CNPJ Inválido\n'; }
		if (!$F('ie'))									{ count = count + 1; erro = erro + '- I.E.\n'; }
		if (!$F('email') || !validaEmail($F('email')))	{ count = count + 1; erro = erro + '- E-mail\n'; }
		if (!$F('senha'))								{ count = count + 1; erro = erro + '- Senha\n'; }
		if (!$F('senha2'))								{ count = count + 1; erro = erro + '- Confirmação de Senha\n'; }
		if ($('senha').value != $('senha2').value)                { count = count + 1; erro = erro + '- As senhas não conferem.\n'; }
		
	}
	
	if (count > 0)	alert(erro);
	else if (enviaCadastroEndereco(form,false)) {
		$(form).submit();
	}
	
}
function editaCadastro(form,tipo_cadastro,atualizacao) {
	var count = 0;
   
	if (tipo_cadastro == 'PF') {
		var erro = '             - FORMULÁRIO DE CLIENTE - \n\nPreencha corretamente os campos abaixo:\n\n';
		
		if (!$('nome_cadastro').value)								{ count = count + 1; erro = erro + '- Nome\n'; }
		if (!$('cpf').value)									{ count = count + 1; erro = erro + '- CPF\n'; }
		else
      if (!checkCPFCNPJ('cpf','cpf'))									{ count = count + 1; erro = erro + '- CPF Inválido\n'; }
		
    if ($('senha').value != $('senha2').value)      { count = count + 1; erro = erro + '- As senhas não conferem.\n'; }
    if (atualizacao != 'atualizacao') {
      if (!$('sexo').value)								{ count = count + 1; erro = erro + '- Sexo\n'; }
  		if (!$('email').value || !validaEmail($('email').value))	{ count = count + 1; erro = erro + '- E-mail\n'; }
		}
	}
	else {
		
		var erro = '             - FORMULÁRIO DE LOJISTA - \n\nPreencha corretamente os campos abaixo:\n\n';
    
		if (!$('razao_social').value)						{ count = count + 1; erro = erro + '- Razão Social\n'; }
		if (!$('cnpj').value)								{ count = count + 1; erro = erro + '- CNPJ\n'; }
		else if (!checkCPFCNPJ('cnpj','cnpj'))									{ count = count + 1; erro = erro + '- CNPJ Inválido\n'; }
		
    if (!$('ie').value)									{ count = count + 1; erro = erro + '- I.E.\n'; }
		if ($('senha').value != $('senha2').value)      { count = count + 1; erro = erro + '- As senhas não conferem.\n'; }
		
    if (atualizacao != 'atualizacao')
      if (!$('email').value || !validaEmail($('email').value))	{ count = count + 1; erro = erro + '- E-mail\n'; }
		
    
	}
	
	if (count > 0)	alert(erro);
	else $(form).submit();
	
} 

function enviaCadastroEndereco(form, submitform) {
	var count = 0;

	var erro = '             - ENDEREÇO DE ENTREGA - \n\nPreencha corretamente os campos abaixo:\n\n';
	
	if (!$F('cep'))									{ count = count + 1; erro = erro + '- CEP\n'; }
	if (!$F('endereco'))							{ count = count + 1; erro = erro + '- Endereço\n'; }
	if (!$F('numero'))								{ count = count + 1; erro = erro + '- Número\n'; }
	if (!$F('bairro'))								{ count = count + 1; erro = erro + '- Bairro\n'; }
	if (!$F('estado_id'))								{ count = count + 1; erro = erro + '- Estado\n'; }
	if (!$F('cidade_id'))								{ count = count + 1; erro = erro + '- Cidade\n'; }
	if (!$F('telefone1'))							{ count = count + 1; erro = erro + '- Telefone 1\n'; }
	
	// Valida o CEP
  var objER = /^[0-9]{5}-[0-9]{3}$/;
	if (!objER.test($F('cep')))
	 { count = count + 1; erro = erro + '- CEP inválido! \n'; }
	         
	if (count > 0)	{
  	alert(erro);
	}
	else {
  	if (submitform)
  		$(form).submit();
  	else 
	    return true;
	
	}
	
}

//----------------------------------------------------------
function enviaSenha(url) {
         if($('email').value == '' || !validaEmail($('email').value))
                  $('esqueceu').innerHTML = 'Email não é válido!';
         else {
               var php = url+"?on=carrinho&in=ajax&ac=esqueceu";
                  var parametros = 'email='+ $('email').value;
                  var ajaxFrete = new Ajax.Request(php,{
                          method: 'post',
                          parameters: parametros,
                          onComplete: function newsReturn(retorno) {
                                             resposta = retorno.responseText;
                                             $('esqueceu').innerHTML = resposta;
                                    }
                  });   
         }
}

//----------------------------------------------------------
function calculaFrete(url) {
         var cep       = $('cep').value;
         var entrega   = $('entrega').value;
     
          $('div_entrega').innerHTML = 'Carregando...';
          var php = url+"?on=carrinho&in=ajax&ac=calculoFrete";
        
          var parametros = 'cep='+ $('cep').value + '&entrega='+ $('entrega').value;
          var ajaxFrete = new Ajax.Request(php,{
                  method: 'post',
                  parameters: parametros,
                  onComplete: function newsReturn(retorno) {
                                      
                                     resposta = retorno.responseText;
                                     valor = resposta.split(';');
                                     
                                     $('div_entrega').innerHTML = 'R$ '+valor[0] ;
                                     $('div_total').innerHTML   = 'R$ '+valor[1] ;
                            }
          });
}
//----------------------------------------------------------

function FormatarInteiro(campo,tecla) {

	var key = '';
	var strCheck = '0123456789';
	var aux = aux2 = '';
	var whichCode = (window.Event) ? tecla.which : tecla.keyCode;

	if (whichCode == 13) return true; // Tecla Enter
	
	if (whichCode == 8) return true; // Tecla Delete
	
	key = String.fromCharCode(whichCode); // Pegando o valor digitado
	
	if (strCheck.indexOf(key) == -1) 
		return false; // Valor inválido (não inteiro)
	
	return true;
}

function tryAjax () {
	
	try {
         ajax = new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch(e) {
         try {
            ajax = new ActiveXObject("Msxml2.XMLHTTP");
         }
	     catch(ex) {
            try {
               ajax = new XMLHttpRequest();
            }
	        catch(exc) {
               alert("Esse browser não tem recursos para uso do Ajax");
               ajax = null;
            }
         }
      }
      
      return ajax;
	
	
}

function ajaxFuncao(php,variaveis,div_id) {
	var ajax = tryAjax();

	if(div_id)
		var div = document.getElementById(div_id);

	if(ajax) {
		
	  ajax.open("POST", php, true); // TRUE PARA NÃO SER SÍNCRONO
	  ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	  
	  ajax.onreadystatechange = function () {
	  	
		if (ajax.readyState == 4) {
			if (ajax.status == 200) {
				
				if(div) {

					div.innerHTML = ajax.responseText;
				
				}
			} else 
				alert('ERRO: '+ajax.statusText);
		}	
			
	  };
	
	  ajax.send(variaveis);
	
	}
}

function ajaxFuncaoCarrinho(php,variaveis,div_id) {
	var ajax = tryAjax();

	if(div_id)
		var div = document.getElementById(div_id);

	if(ajax) {
		
	  ajax.open("POST", php, true); // TRUE PARA NÃO SER SÍNCRONO
	  ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	  
	  ajax.onreadystatechange = function () {
	  	
		if (ajax.readyState == 4) {
			if (ajax.status == 200) {
				
				if(div) {

					div.innerHTML = ajax.responseText;
				  ajaxFuncao('index.php?on=carrinho&in=ajax&ac=valorTotal','','div_total');
				
				}
			} else 
				alert('ERRO: '+ajax.statusText);
		}	
			
	  };
	
	  ajax.send(variaveis);
	
	}
}
function ajaxRedirect(php,variaveis,link) {
	var ajax = tryAjax();

	if(ajax) {
		
	  ajax.open("POST", php, true); // TRUE PARA NÃO SER SÍNCRONO
	  ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	  
	  ajax.onreadystatechange = function () {
	  	
		if (ajax.readyState == 4) {
			if (ajax.status == 200) {
				window.location.replace(link); 
			}
			}	
			
	  };
	  ajax.send(variaveis);
	
	}
}

function postaForm(frm,link,div) {

	    var variaveis='';
		
	    for (i=0;i<document.forms.length;i++) {
	      if (document.forms[i].name == frm) {
	        for (j=0;j<document.forms[i].elements.length;j++) {
	        	
	          obj = document.forms[i].elements[j];
	          name = document.forms[i].elements[j].name;
	          value = document.forms[i].elements[j].value;
	          type = document.forms[i].elements[j].type;
	          
	          if (type == 'radio' || type == 'checkbox') {
	          	
	          	if (obj.checked)
	          		variaveis = variaveis + "&" + name + "=" + value;
	          	
	          }
	          else
		          variaveis = variaveis + "&" + name + "=" + value;
	          
	        }
	      }
	    }

	    ajaxFuncao(link+variaveis,'',div);
}
function votoEnquete () {

  postaForm('form_enquete','index.php?on=ajax&in=enquete&respondeu=1','votoEnqueteResultado');
 
}

function SomenteNumero(e){
    var tecla=(window.event)?event.keyCode:e.which;
    if((tecla > 47 && tecla < 58)) return true;
    else{
    if (tecla != 8) return false;
    else return true;
    }
}

function FormataValor(campo,tammax,teclapres) {
	var tecla = teclapres.keyCode;
	vr = campo.value;
	vr = vr.replace( "/", "" );
	vr = vr.replace( "/", "" );
	vr = vr.replace( ",", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	tam = vr.length;

//	if (tam < tammax && tecla != 8){ tam = vr.length + 1 ; }

	if (tecla == 8 ){	tam = tam - 1 ; }
	
	if (tam < tammax) {
  	if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ){
  		if ( tam <= 3 ){ 
  	 		campo.value = vr ; }
  	 	if ( (tam > 3) && (tam <= 5) ){
  	 	campo.value = vr.substr( 0, tam - 2 ) + ',' + vr.substr( tam - 2, tam ) ; }
  	 	if ( (tam >= 6) && (tam <= 8) ){
  	 		campo.value = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; }
  	 	if ( (tam >= 9) && (tam <= 11) ){
  	 		campo.value = vr.substr( 0, tam - 8 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; }
  	 	if ( (tam >= 12) && (tam <= 14) ){
  	 		campo.value = vr.substr( 0, tam - 11 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; }
  	 	if ( (tam >= 15) && (tam <= 17) ){
  	 		campo.value = vr.substr( 0, tam - 14 ) + '.' + vr.substr( tam - 14, 3 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ;}
  	}
	}
		
}
/*
function calculaFrete(php,phptotal) {
	var ajax = tryAjax();
	var variaveis = 'cep='+$('cep').value+'&entrega='+$('entrega').value;
  var div = 'div_entrega';
  
  $(div).innerHTML = 'Carregando...';

	if(ajax) {
		
	  ajax.open("POST", php, true); // TRUE PARA NÃO SER SÍNCRONO
	  ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	  
	  ajax.onreadystatechange = function () {
	  	
		if (ajax.readyState == 4) {
			if (ajax.status == 200) {
				
					$(div).innerHTML = ajax.responseText;
				  ajaxFuncao(phptotal,'','div_total');

			} else 
				alert('ERRO: '+ajax.statusText);
		}	
			
	  };
	
	  ajax.send(variaveis);
	
	}
}*/

function avisoEmail(url, produto_id) {

    email = jQuery('#emailEnviar').val();
    variaveis = 'email='+email+'&produto_id='+produto_id;
    
    jQuery.ajax({
      type: "POST",
      url: url+"?on=produtos&in=ajax&ac=avisoEmail",
      data: variaveis,          
      success: function(retorno){
        jQuery('.itemIndisponivel').find(':input').each(function() {
	         switch(this.type) {
	               case 'text':
	               case 'textarea':
  	                 jQuery(this).val('');
  	       }
  	    });
        jQuery('.textoIndisponivel').show();
        avisoEmailEnviar(url); 
      }
    });
    
}
