// Função que Lê os conteúdos carregados por Ajax para procurar scripts JS dentro de tags <script>

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);

        }

    }

}
/* Enviar iColabora pr Ajax*/
function EnviaiColabora(codpedido) {
	
   var ajaxObj;
   
   try {
      // Firefox, Opera 8.0+, Safari...
      ajaxObj=new XMLHttpRequest();
   } catch (e) {
      // Internet Explorer
      try {
         ajaxObj=new ActiveXObject("Msxml2.XMLHTTP");
      } catch (e) {
         try {
            ajaxObj=new ActiveXObject("Microsoft.XMLHTTP");
         } catch (e) {
            alert("Seu navegador não possui suporte ao AJAX!");
            return false;
         }
      }
   }
   ajaxObj.onreadystatechange=function() {
	 
      if(ajaxObj.readyState==4) {
         document.getElementById("div-icolabora").innerHTML=ajaxObj.responseText;
		  extraiScript(ajaxObj.responseText);
      }
   }
   
   ajaxObj.open("GET","http://www.vivaexperiencias.net/icolabora.php?codpedido="+codpedido,true);
   ajaxObj.send(null);
}
	
	
	

// Abrir Submenu no Internet Explorer 7

sfHover = function() {
	var sfEls = document.getElementById("nav").getElementsByTagName("LI");
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className+=" sfhover";
		}
		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
		}
	}
}
if (window.attachEvent) window.attachEvent("onload", sfHover);

// Popup centralizado

function popup(caminho1,nome1,largura1,altura1,rolagem1) {
	var esquerda1 = (screen.width - largura1) / 2;
	var cima1 = (screen.height - altura1) / 2 -50;
	window.open(caminho1,nome1,'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=' + rolagem1 + ',resizable=no,copyhistory=no,top=' + cima1 + ',left=' + esquerda1 + ',width=' + largura1 + ',height=' + altura1);
}

/* Carregar foto por Ajax*/
function carrega_foto(codexperiencia, foto) {
	
   var ajaxObj;
   
   try {
      // Firefox, Opera 8.0+, Safari...
      ajaxObj=new XMLHttpRequest();
   } catch (e) {
      // Internet Explorer
      try {
         ajaxObj=new ActiveXObject("Msxml2.XMLHTTP");
      } catch (e) {
         try {
            ajaxObj=new ActiveXObject("Microsoft.XMLHTTP");
         } catch (e) {
            alert("Seu navegador não possui suporte ao AJAX!");
            return false;
         }
      }
   }
   ajaxObj.onreadystatechange=function() {
	   document.getElementById("foto-experiencia").innerHTML="<img src=\"http://www.vivaexperiencias.net/adm/images/loading2.gif\" alt=\"\" />";
      if(ajaxObj.readyState==4) {
         document.getElementById("foto-experiencia").innerHTML=ajaxObj.responseText;
      }
   }
   
   ajaxObj.open("GET","http://www.vivaexperiencias.net/experiencia-foto.php?codexperiencia="+codexperiencia+"&foto="+foto,true);
   ajaxObj.send(null);
}

/* Carregar municipios por Ajax*/
function listamunicipios(uf) {
	
   var ajaxObj;
   
   try {
      // Firefox, Opera 8.0+, Safari...
      ajaxObj=new XMLHttpRequest();
   } catch (e) {
      // Internet Explorer
      try {
         ajaxObj=new ActiveXObject("Msxml2.XMLHTTP");
      } catch (e) {
         try {
            ajaxObj=new ActiveXObject("Microsoft.XMLHTTP");
         } catch (e) {
            alert("Seu navegador não possui suporte ao AJAX!");
            return false;
         }
      }
   }
   ajaxObj.onreadystatechange=function() {
	   document.getElementById("lista-municipios").innerHTML="Carregando...";
      if(ajaxObj.readyState==4) {
         document.getElementById("lista-municipios").innerHTML=ajaxObj.responseText;
      }
   }
   
   ajaxObj.open("GET","http://www.vivaexperiencias.net/listamunicipios.php?coduf="+uf,true);
   ajaxObj.send(null);
}


// 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){	
	switch (nomeform){
		case "formcadastro":
		    
		  if (document.formcadastro.nome.value==""){
			  alert("Por favor, insira o nome!");
			  document.formcadastro.nome.focus();
			  return false;
			  }
	       if (document.formcadastro.cpf.value==""){
			  alert("Por favor, insira o cpf!");
			  document.formcadastro.cpf.focus();
			  return false;
			  }
			    if (document.formcadastro.rg.value==""){
			  alert("Por favor, insira o rg!");
			  document.formcadastro.rg.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.estadocivil.selectedIndex==0){
			  alert("Por favor, informe o estado civil!");
			  document.formcadastro.estadocivil.focus();
			  return false;
			  }
			  
			    if (document.formcadastro.email.value==""){
			  alert("Por favor, insira o email!");
			  document.formcadastro.email.focus();
			  return false;
			  }
			  
			  if (document.formcadastro.senha.value==""){
			  alert("Por favor, insira a senha!");
			  document.formcadastro.senha.focus();
			  return false;
			  }
		  
		      if (document.formcadastro.senha2.value==""){
			  alert("Por favor, insira a senha novamente!");
			  document.formcadastro.senha2.focus();
			  return false;
			  }
			  
			  if (document.formcadastro.senha.value != document.formcadastro.senha2.value){
			  alert("Por favor, verifique a senha!");
			  document.formcadastro.senha2.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.telefone.value==""){
			  alert("Por favor, insira o telefone!");
			  document.formcadastro.telefone.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 (document.formcontato.dddtel.value==""){
			  alert("Por favor, insira o DDD do telefone!");
			  document.formcontato.dddtel.focus();
			  return false;
			  }
			    if (document.formcontato.telefone.value==""){
			  alert("Por favor, insira o telefone!");
			  document.formcontato.telefone.focus();
			  return false;
			  }
			    if (document.formcontato.cidade.value==""){
			  alert("Por favor, insira a cidade!");
			  document.formcontato.cidade.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 "formparceiros":
		    
		  if (document.formparceiros.nome.value==""){
			  alert("Por favor, insira o nome!");
			  document.formparceiros.nome.focus();
			  return false;
			  }
	       if (document.formparceiros.email.value==""){
			  alert("Por favor, insira o email!");
			  document.formparceiros.email.focus();
			  return false;
			  }
			    if (document.formparceiros.dddtel.value==""){
			  alert("Por favor, insira o DDD do telefone!");
			  document.formparceiros.dddtel.focus();
			  return false;
			  }
			    if (document.formparceiros.telefone.value==""){
			  alert("Por favor, insira o telefone!");
			  document.formparceiros.telefone.focus();
			  return false;
			  }
			    if (document.formparceiros.cidade.value==""){
			  alert("Por favor, insira a cidade!");
			  document.formparceiros.cidade.focus();
			  return false;
			  }
			  
			    if (document.formparceiros.empresa.value==""){
			  alert("Por favor, insira a empresa!");
			  document.formparceiros.empresa.focus();
			  return false;
			  }
			  
			  if (document.formparceiros.mensagem.value==""){
			  alert("Por favor, insira a mensagem!");
			  document.formparceiros.mensagem.focus();
			  return false;
			  }
		  
		  document.formparceiros.submit();
		  
        break;
		
		case "formtrabalhe":
		    
		  if (document.formtrabalhe.nome.value==""){
			  alert("Por favor, insira o nome!");
			  document.formtrabalhe.nome.focus();
			  return false;
			  }
	       if (document.formtrabalhe.email.value==""){
			  alert("Por favor, insira o email!");
			  document.formtrabalhe.email.focus();
			  return false;
			  }
			    if (document.formtrabalhe.dddtel.value==""){
			  alert("Por favor, insira o DDD do telefone!");
			  document.formtrabalhe.dddtel.focus();
			  return false;
			  }
			    if (document.formtrabalhe.telefone.value==""){
			  alert("Por favor, insira o telefone!");
			  document.formtrabalhe.telefone.focus();
			  return false;
			  }
			 
			  if (document.formtrabalhe.cidade.value==""){
			  alert("Por favor, insira a cidade!");
			  document.formtrabalhe.cidade.focus();
			  return false;
			  }
			  
			  if (document.formtrabalhe.area.value==""){
			  alert("Por favor, insira a area pretendida!");
			  document.formtrabalhe.area.focus();
			  return false;
			  }

              if (document.formtrabalhe.descricao.value==""){
			  alert("Por favor, insira a descricao!");
			  document.formtrabalhe.descricao.focus();
			  return false;
			  }

		  document.formtrabalhe.submit();
		  
        break;
		
		case "formlogin":
		    
		  if (document.formlogin.email.value==""){
			  alert("Por favor, insira o email!");
			  document.formlogin.email.focus();
			  return false;
			  }
   	      if (!VerificaEmail(document.formlogin.email.value)) {
			alert("Por favor, verifique o email!");
			document.formlogin.email.focus();
			return false;
			}		  
	     if (document.formlogin.senha.value==""){
			  alert("Por favor, insira a senha!");
			  document.formlogin.senha.focus();
			  return false;
			  }	   
   		
          document.formlogin.submit();
		  
        break;
		
		case "formamigo":
		    
		  if (document.formamigo.nome.value==""){
			  alert("Por favor, insira o seu nome!");
			  document.formamigo.nome.focus();
			  return false;
			  }
		  if (document.formamigo.email.value==""){
			  alert("Por favor, insira o seu e-mail!");
			  document.formamigo.email.focus();
			  return false;
			  }
   	      if (!VerificaEmail(document.formamigo.email.value)) {
			alert("Por favor, verifique o seu e-mail!");
			document.formamigo.email.focus();
			return false;
			}
			
			if (document.formamigo.nome_amigo.value==""){
			  alert("Por favor, insira o nome de seu amigo!");
			  document.formamigo.nome_amigo.focus();
			  return false;
			  }
		  if (document.formamigo.email_amigo.value==""){
			  alert("Por favor, insira o e-mail de seu amigo!");
			  document.formamigo.email_amigo.focus();
			  return false;
			  }
   	      if (!VerificaEmail(document.formamigo.email_amigo.value)) {
			alert("Por favor, verifique o e-mail de seu amigo!");
			document.formamigo.email_amigo.focus();
			return false;
			}
	      
   		
          document.formamigo.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;
}

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

//XMLHTTPREQUEST COM POST
function loadXMLDocFrete(url)
{
    req = null;
    // Procura por um objeto nativo (Mozilla/Safari)
    if (window.XMLHttpRequest) {
	
		// monta a string de dados a ser enviada p/script no servidor 
  // 
  var query = ''; 
  for (var j=0, elm; (elm = document.FinalizarPedido.elements[j]); j++) 
  { 
    var name = elm.getAttribute('name'); 
    if (name) { 
      if (query) query += '&'; 
      query += name + '=' + elm.value; 
    } 
  } 

        req = new XMLHttpRequest();
        req.onreadystatechange = processReqChangeFrete;
        req.open("POST", url, true); 
        req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); 
        req.send(query); 
    // Procura por uma versao ActiveX (IE)
    } else if (window.ActiveXObject) {
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req) {
			
					// monta a string de dados a ser enviada p/script no servidor 
  // 
  var query = ''; 
  for (var j=0, elm; (elm = document.FinalizarPedido.elements[j]); j++) 
  { 
    var name = elm.getAttribute('name'); 
    if (name) { 
      if (query) query += '&'; 
      query += name + '=' + elm.value; 
	  
    } 
  } 
			
            req.onreadystatechange = processReqChangeFrete;
            req.open("POST", url, true); 
            req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); 
            req.send(query); 
        }
    }
}

function processReqChangeFrete()
{
			//document.getElementById("acao").innerHTML = "<img src='images/loading.gif' width='111' height='11' />";
    // 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("recebe-frete").innerHTML = req.responseText;
	// executa scripts
            extraiScript(req.responseText);
        } else {
            alert("Houve um problema ao obter os dados:\n" + req.statusText);
        }
    }
}

function CalculaFrete()
{
    loadXMLDocFrete("carrinho-frete.php");
}	
