function extraiScript(texto){

//Maravilhosa função feita pelo SkyWalker.TO do imasters/forum

//http://forum.imasters.com.br/index.php?showtopic=165277

    // inicializa o inicio ><

    var ini = 0;

    // loop enquanto achar um script

    while (ini!=-1){

        // procura uma tag de script

        ini = texto.indexOf('<script', ini);

        // se encontrar

        if (ini >=0){

            // define o inicio para depois do fechamento dessa tag

            ini = texto.indexOf('>', ini) + 1;

            // procura o final do script

            var fim = texto.indexOf('</script>', ini);

            // extrai apenas o script

            codigo = texto.substring(ini,fim);

            // executa o script

            //eval(codigo);

            novo = document.createElement("script");

            novo.text = codigo;

            document.body.appendChild(novo);

        }

    }

}


function VerificaEmail(email) 
{
	if (!email) return false;
		var  BadChars = "*|,\":<>[]{}`\';()&$#% ";
		var  GoodChars = "@.";   
		
		for (var i = 0; i < email.length; i++) {
			if (BadChars.indexOf(email.charAt(i)) != -1) 
			{
				return false;
			}
		}
		
		for (var i = 0; i < GoodChars.length; i++) 
		{
			if (email.indexOf(GoodChars.charAt(i)) == -1) 
			{
				return false;
			}
		}
	 	
		if (email.indexOf ('@.',0) != -1 || email.indexOf ('.@',0) != -1) 
		{
			return false;
		}
	return true;
}

function EsqueciSenha() 
{
    var email = document.formlogin.email_login.value;
	
	
	if (email != ""){
		
	  if (!VerificaEmail(email)) {
		    alert("Por favor, verifique o seu e-mail!");
			document.formlogin.email_login.focus();
			}else{
			loadXMLDoc_esquecisenha("esqueci_senha.php", email);
				}
				
    }else{			
		 alert("Por favor, informe o seu e-mail!");
		 document.formlogin.email_login.focus();
		 }
}

function loadXMLDoc_esquecisenha(url, email)
{
    req = null;
    // Procura por um objeto nativo (Mozilla/Safari)
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
        req.onreadystatechange = processReqChange_esquecisenha;
        req.open("GET", url + "?email=" + email , true);
        req.send(null);
    // Procura por uma versao ActiveX (IE)
    } else if (window.ActiveXObject) {
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req) {
            req.onreadystatechange = processReqChange_esquecisenha;
            req.open("GET", url + "?email=" + email , true);
            req.send();
        }
    }
}

function processReqChange_esquecisenha()
{
    // apenas quando o estado for "completado"
    if (req.readyState == 4) {
        // apenas se o servidor retornar "OK"
        if (req.status == 200) {
            // procura pela div id="atualiza" e insere o conteudo
            // retornado nela, como texto HTML
			document.getElementById('resposta').style.display = 'block';
            document.getElementById('resposta').innerHTML = req.responseText;
			// executa scripts
            extraiScript(req.responseText);
        } else {
            alert("Houve um problema ao obter os dados:\n" + req.statusText);
        }
    }
}


// Carregar Select de Bairros por Ajax
function loadXMLDoc2(url, cidade, bairro)
{
    req = null;
    // Procura por um objeto nativo (Mozilla/Safari)
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
        req.onreadystatechange = processReqChange2;
        req.open("GET", url+'?cidade='+cidade+'&bairro='+bairro, true);
        req.send(null);
    // Procura por uma versao ActiveX (IE)
    } else if (window.ActiveXObject) {
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req) {
            req.onreadystatechange = processReqChange2;
            req.open("GET", url+'?cidade='+cidade+'&bairro='+bairro, true);
            req.send();
        }
    }
}

function processReqChange2()
{
	document.getElementById('frete-atualizado').innerHTML = "Carregando...";
    // apenas quando o estado for "completado"
    if (req.readyState == 4) {
        // apenas se o servidor retornar "OK"
        if (req.status == 200) {
            // procura pela div id="atualiza" e insere o conteudo
            // retornado nela, como texto HTML
            document.getElementById('frete-atualizado').innerHTML = req.responseText;
			// executa scripts
           // extraiScript(req.responseText);
        } else {
            alert("Houve um problema ao obter os dados:\n" + req.statusText);
        }
    }
}

function AtualizaFrete(cidade, bairro)
{
    loadXMLDoc2("carrinho-atualizado.php", cidade, bairro);
}



// Mostra ou esconde o formulário de cadastro. Se mostra, ele esconde o formulário de login.
function mostra_form_cadastro(){
	
   obj = document.getElementById("cadastro");
   obj2 = document.getElementById("login");
   obj3 = document.getElementById("erro");
   
   if (obj.style.display == "block"){
	   obj.style.display = 'none';	   
	   }else{
         obj.style.display = 'block';
		 obj2.style.display = 'none';
		 if (obj3) {obj3.style.display = 'none';}
	   }
   document.getElementById("resposta").style.display = 'none';
}

// Mostra ou esconde o formulário de login. Se mostra, ele esconde o formulário de cadastro.
function mostra_form_login(){
	
   obj = document.getElementById("login");
   obj2 = document.getElementById("cadastro");
   obj3 = document.getElementById("erro");
   
   if (obj.style.display == "block"){
	   obj.style.display = 'none';	
	   if (obj3) {obj3.style.display = 'none';}
	   }else{
         obj.style.display = 'block';
		 obj2.style.display = 'none';
	   }
     document.getElementById("resposta").style.display = 'none';
 
}

// Carregar Select de Bairros por Ajax
function loadXMLDoc(url, valor)
{
    req = null;
    // Procura por um objeto nativo (Mozilla/Safari)
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
        req.onreadystatechange = processReqChange;
        req.open("GET", url+'?cidade='+valor, true);
        req.send(null);
    // Procura por uma versao ActiveX (IE)
    } else if (window.ActiveXObject) {
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req) {
            req.onreadystatechange = processReqChange;
            req.open("GET", url+'?cidade='+valor, true);
            req.send();
        }
    }
}

function processReqChange()
{
	document.getElementById('bairros').innerHTML = "Carregando...";
    // apenas quando o estado for "completado"
    if (req.readyState == 4) {
        // apenas se o servidor retornar "OK"
        if (req.status == 200) {
            // procura pela div id="atualiza" e insere o conteudo
            // retornado nela, como texto HTML
            document.getElementById('bairros').innerHTML = req.responseText;
			// executa scripts
           // extraiScript(req.responseText);
        } else {
            alert("Houve um problema ao obter os dados:\n" + req.statusText);
        }
    }
}

function listabairros(valor)
{
    loadXMLDoc("listabairros.php", valor);
}

function mostrar_inst(valor)
{
      if (valor == 'D'){
		  document.getElementById('instdeposito').style.display = 'block';
		  document.getElementById('instcartao').style.display = 'none';
		  }
	  else if (valor == 'V' || valor == 'M'){
  		  document.getElementById('instdeposito').style.display = 'none';
		  document.getElementById('instcartao').style.display = 'block';
		  }
	  
}

/*// Máscaras para formulários
Mascaras = {
IsIE: navigator.appName.toLowerCase().indexOf('microsoft')!=-1,
AZ: /[A-Z]/i,
Acentos: /[À-ÿ]/i,
Num: /[0-9]/,
carregar: function(parte){
 var Tags = ['input','textarea'];
 if (typeof parte == "undefined") parte = document;
 for(var z=0;z<Tags.length;z++){
  Inputs=parte.getElementsByTagName(Tags[z]);
  for(var i=0;i<Inputs.length;i++)
   if(('button,image,hidden,submit,reset').indexOf(Inputs[i].type.toLowerCase())==-1)
    this.aplicar(Inputs[i]);
 }
},
aplicar: function(campo){
 tipo = campo.getAttribute('tipo');
 if (!tipo || campo.type == "select-one") return;
 orientacao = campo.getAttribute('orientacao');
 mascara = campo.getAttribute('mascara');
 if (tipo.toLowerCase() == "decimal"){
  orientacao = "esquerda";
  casasdecimais = campo.getAttribute('casasdecimais');
  tamanho = campo.getAttribute('maxLength');
  if (!tamanho || tamanho > 50)
   tamanho = 10;
  if (!casasdecimais)
   casasdecimais = 2;
  campo.setAttribute("mascara", this.geraMascaraDecimal(tamanho, casasdecimais));
  campo.setAttribute("tipo", "numerico");
  campo.setAttribute("orientacao", orientacao);
 }
 if (orientacao && orientacao.toLowerCase() == "esquerda") campo.style.textAlign = "right";
 if (mascara) campo.setAttribute("maxLength", mascara.length);
 if (tipo){
  campo.onkeypress = function(e){ return Mascaras.onkeypress(e?e:event); };
  campo.onkeyup = function(e){ Mascaras.onkeyup(e?e:event, campo) };
 }
 campo.setAttribute("snegativo", ((campo.value).substr(0,1) == "-" ? "s" : "n"));
},
onkeypress: function(e){
 KeyCode = this.IsIE ? event.keyCode : e.which;
 campo =  this.IsIE ? event.srcElement : e.target;
 readonly = campo.getAttribute('readonly');
 if (readonly) return;
 maxlength = campo.getAttribute('maxlength');
 pt = campo.getAttribute('pt');
 selecao = this.selecao(campo);
 if (selecao.length > 0 && KeyCode != 0){
  campo.value = ""; return true;
 }
 if (KeyCode == 0) return true;
 Char = String.fromCharCode(KeyCode);
 valor = campo.value;
 mascara = campo.getAttribute('mascara');
 if (KeyCode != 8){
  tipo = campo.getAttribute('tipo').toLowerCase();
  negativo = campo.getAttribute('negativo');
  if(negativo && KeyCode == 45){
   snegativo = campo.getAttribute('snegativo');
   snegativo = (snegativo == "s" ? "n" : "s");
   campo.setAttribute("snegativo", snegativo);
  }else{
   valor += Char
   if (tipo == "numerico" && Char.search(this.Num) == -1) return false;
   if (KeyCode != 32 && tipo == "caracter" && Char.search(this.AZ) == -1 && Char.search(this.Acentos) == -1) return false;
  }
 }
 if (mascara){
  this.aplicarMascara(campo, valor);
  return false;
 }
 return true;
},
onkeyup: function(e, campo){
 KeyCode = this.IsIE ? event.keyCode : e.which;
 if (KeyCode != 9 && KeyCode != 16 && KeyCode != 109){
  valor = campo.value;
  if (KeyCode == 8 && !this.IsIE) valor = valor.substr(0,valor.length-1);
  this.aplicarMascara(campo, valor);
 }
},
aplicarMascara: function(campo, valor){
 mascara = campo.getAttribute('mascara');
 if (!mascara) return;
 negativo = campo.getAttribute('negativo');
 snegativo = campo.getAttribute('snegativo');
 if (negativo && valor.substr(0,1) == "-") 
  valor = valor.substr(1,valor.length-1);
 orientacao = campo.getAttribute('orientacao');
 var i = 0;
 for(i=0;i<mascara.length;i++){
  caracter = mascara.substr(i,1);
  if (caracter != "#") valor = valor.replace(caracter, "");
 }
 retorno = "";
 if (orientacao != "esquerda"){
  contador = 0;
  for(i=0;i<mascara.length;i++){
   caracter = mascara.substr(i,1);
   if (caracter == "#"){
    retorno += valor.substr(contador,1);
    contador++;
   }else
    retorno += caracter;
   if(contador >= valor.length) break;
  }
 }else{
  contador = valor.length-1;
  for(i=mascara.length-1;i>=0;i--){
   if(contador < 0) break;
   caracter = mascara.substr(i,1);
   if (caracter == "#"){
    retorno = valor.substr(contador,1) + retorno;
    contador--;
   }else
    retorno = caracter + retorno;
  }
 }
 if (negativo && snegativo == "s")
  retorno = "-" + retorno;
 campo.value = retorno;
},
geraMascaraDecimal: function(tam, decimais){
 var retorno = ""; var contador = 0; var i = 0;
 decimais = parseInt(decimais);
 for (i=0;i<(tam-(decimais+1));i++){
  retorno = "#" + retorno;
  contador++;
  if (contador == 3){
   retorno = "." + retorno;
   contador=0;
  }
 }
 retorno = retorno + ",";
 for (i=0;i<decimais;i++) retorno += "#";
 return retorno;
},
selecao: function(campo){
 if (this.IsIE)
  return document.selection.createRange().text;
 else
  return (campo.value).substr(campo.selectionStart, (campo.selectionEnd - campo.selectionStart));
},
formataValor: function (valor, decimais){
 valor = valor.split('.');
 if (valor.length == 1) valor[1] = "";
 for(var i=valor[1].length;i<decimais;i++)
  valor[1] += "0"; 
 valor[1] = valor[1].substr(0,2);
 return (valor[0] + "." + valor[1]);
}
};*/

function valida_form(nomeform,validate){	
    
    
    
    
    
    
    // Validar CIDADES restringidas por data
    if(validate!=undefined){
        date = new Date();
        data_ext = date.getDate()+"/"+date.getMonth();
        
    
        cidade = document.getElementById("cidade").value;
        dia_entrega = document.getElementById("entrega").value;
     
        if(dia_entrega=="07/05/2011" || dia_entrega == "08/05/2011"){
    
            switch(cidade){
                case "Praia Grande":
                case "Guaruja":
                case "Cubatao":
                    alert("Caro usuário, durante os dias 07 e 08 de maio, não haverá entregas para a respectivas cidades: Praia Grange, Cubatão e Guarujá. por favor selecione uma outra data.");          
                    return false;
                    break;
            }
        }
    } 
    // end
    
     
     
    
    

	switch (nomeform){
		case "formcadastro":
 
            
            
		  if (document.formcadastro.nome.value==""){
			  alert("Por favor, insira o nome!");
			  document.formcadastro.nome.focus();
			  return false;
			  } 
			  
			  if (document.formcadastro.nascimento.value==""){
			  alert("Por favor, insira a data de nascimento!");
			  document.formcadastro.nascimento.focus();
			  return false;
			  }
	       if (document.formcadastro.cpf.value==""){
			  alert("Por favor, insira o cpf!");
			  document.formcadastro.cpf.focus();
			  return false;
			  } 
			  
			  if (document.formcadastro.email.value==""){
			  alert("Por favor, insira o email!");
			  document.formcadastro.email.focus();
			  return false;
			  }
			  if (!VerificaEmail(document.formcadastro.email.value)) {
			alert("Por favor, verifique o email!");
			document.formcadastro.email.focus();
			return false;
			}
			  
			    		  
			 if (document.formcadastro.endereco.value==""){
			  alert("Por favor, insira o endereco!");
			  document.formcadastro.endereco.focus();
			  return false;
			  }
			  
			  if (document.formcadastro.numero.value==""){
			  alert("Por favor, insira o numero!");
			  document.formcadastro.numero.focus();
			  return false;
			  }
			  
			  if (document.formcadastro.cep.value==""){
			  alert("Por favor, insira o CEP!");
			  document.formcadastro.cep.focus();
			  return false;
			  }
			  
			  if (document.formcadastro.dddtel.value==""){
			  alert("Por favor, insira o DDD do telefone!");
			  document.formcadastro.dddtel.focus();
			  return false;
			  }
			  
			  if (document.formcadastro.telefone.value==""){
			  alert("Por favor, insira o telefone!");
			  document.formcadastro.telefone.focus();
			  return false;
			  }
			   if (document.formcadastro.senha.value==""){
			  alert("Por favor, insira a senha!");
			  document.formcadastro.senha.focus();
			  return false;
			  }
	 	
	
		  document.formcadastro.submit();
		  
        break;
		
		case "formcontato":
		    
		  if (document.formcontato.nome.value==""){
			  alert("Por favor, insira o nome!");
			  document.formcontato.nome.focus();
			  return false;
			  }
	       if (document.formcontato.email.value==""){
			  alert("Por favor, insira o email!");
			  document.formcontato.email.focus();
			  return false;
			  }
		if (!VerificaEmail(document.formcontato.email.value)) {
			alert("Por favor, verifique o email!");
			document.formcontato.email.focus();
			return false;
			}
			  
			    if (document.formcontato.assunto.value==""){
			  alert("Por favor, insira o assunto!");
			  document.formcontato.assunto.focus();
			  return false;
			  }
			  
			  if (document.formcontato.mensagem.value==""){
			  alert("Por favor, insira a mensagem!");
			  document.formcontato.mensagem.focus();
			  return false;
			  }
		  
		  document.formcontato.submit();
		  
        break;
		
		case "formentrega":
		    
		  if (document.formentrega.nome_entrega.value==""){
			  alert("Por favor, insira o nome do destinatario!");
			  document.formentrega.nome_entrega.focus();
			  return false;
			  }
	       if (document.formentrega.entrega.value==""){
			  alert("Por favor, insira a data de entrega!");
			  document.formentrega.entrega.focus();
			  return false;
			  }
			    if (document.formentrega.endereco.value==""){
			  alert("Por favor, insira o endereco de entrega!");
			  document.formentrega.endereco.focus();
			  return false;
			  }
			    if (document.formentrega.numero.value==""){
			  alert("Por favor, insira o numero do endereco de entrega!");
			  document.formentrega.numero.focus();
			  return false;
			  }
			    if (document.formentrega.cep.value==""){
			  alert("Por favor, insira o cep do endereco de entrega!");
			  document.formentrega.cep.focus();
			  return false;
			  }
              
              checked_pagamento = "";
                for( i = 0; i < document.formentrega.pagamentos.length; i++ )
                {
                    if( document.formentrega.pagamentos[i].checked == true ){
                        
                        checked_pagamento = document.formentrega.pagamentos[i].value;
                    }
                }
 
                
                
			    if (checked_pagamento==""){
    			  alert("Por favor, escolha a forma de pagamento!");
    			  document.formentrega.pagamentos.focus();
    			  return false;
			  }
			 
		  
		  document.formentrega.submit();
		  
        break;
		
				
		case "formlogin":
		    
		  if (document.formlogin.email_login.value==""){
			  alert("Por favor, insira o email!");
			  document.formlogin.email_login.focus();
			  return false;
			  }
   	      if (!VerificaEmail(document.formlogin.email_login.value)) {
			alert("Por favor, verifique o email!");
			document.formlogin.email_login.focus();
			return false;
			}		  
	     if (document.formlogin.senha_login.value==""){
			  alert("Por favor, insira a senha!");
			  document.formlogin.senha_login.focus();
			  return false;
			  }	   
   		
          document.formlogin.submit();
		  
        break;
		
		
		
		}
	
}

function VerificaEmail(email) 
{
	if (!email) return false;
		var  BadChars = "*|,\":<>[]{}`\';()&$#% ";
		var  GoodChars = "@.";   
		
		for (var i = 0; i < email.length; i++) {
			if (BadChars.indexOf(email.charAt(i)) != -1) 
			{
				return false;
			}
		}
		
		for (var i = 0; i < GoodChars.length; i++) 
		{
			if (email.indexOf(GoodChars.charAt(i)) == -1) 
			{
				return false;
			}
		}
	 	
		if (email.indexOf ('@.',0) != -1 || email.indexOf ('.@',0) != -1) 
		{
			return false;
		}
	return true;
}
