var firefox = false;
if (!document.all){ firefox=true; }

try{
    xmlhttp = new XMLHttpRequest();
}catch(ee){
    try{
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    }catch(e){
        try{
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }catch(E){
            xmlhttp = false;
        }
    }
}

function opener_popup(url){
	window.opener.location = url;
}

function verificaEnter(funcao){
	if (event.keyCode == 13){
		eval(funcao);
	}
}

function showHide(id){
	obj = document.getElementById(id);
	if(obj.style.display != 'block'){
		obj.style.display = 'block';
	}else{
		obj.style.display = 'none';
	}
}
function showHideTr(id){
	obj = document.getElementById(id);
	if(firefox){	
		if(obj.style.display != 'table-row'){
			obj.style.display = 'table-row';
		} else {
			obj.style.display = 'none';
		}
	} else {
		if(obj.style.display != 'block'){
			obj.style.display = 'block';
		} else {
			obj.style.display = 'none';
		}
	}

}

function showHideDiv(id){
	obj = document.getElementById(id);
	if(obj.style.visibility != 'visible'){
		obj.style.visibility = 'visible';
	}else{
		obj.style.visibility = 'hidden';
	}
}

function redimensiona_iframe(id, altura){
	obj = window.parent.document.getElementById(id);
	obj.style.height = altura + 'px';
}

function popup (largura, altura, nome, scrollbar, url) {
	resolucaox = screen.width/2;
	resolucaoy = screen.height/2;
	pontox = resolucaox - (largura/2);
	pontoy = resolucaoy - (altura/2);
	window.open(url, nome, "scrollbars=" + scrollbar + ", resizable=yes, width=" + largura + ", height=" + altura + ", left=" + pontox + ", top=" + pontoy);
}

function FormataData(Campo, teclapres){
	if(window.event){
		var tecla = teclapres.keyCode;
	} else {
		tecla = teclapres.which;
	}
	var vr = new String(Campo.value);
	vr = vr.replace("-", "");
	tam = vr.length + 1;
	if (tecla != 9 && tecla != 8){
		if (tam > 2 && tam < 4){
			Campo.value = vr.substr(0,2) + '-' + vr.substr(2,tam);
		}
		if (tam >= 5 && tam < 7){
			Campo.value = vr.substr(0,2) + '-' + vr.substr(2,4) + '-' + vr.substr(6,tam-6);
		}
	}
}
function confere_email(email){
	if ((email.indexOf("@",0) < 1) || (email.indexOf("@",0) == email.length - 1)) {
		alert("E-mail inv�lido.");
		return false;
	} else {
		return true;
	}
}
function confere_numerico(campo, nome_campo){
	if(campo=='' || isNaN(campo)){
		alert("O campo '"+nome_campo+"' deve ser num�rico.");
		return false;
	} else {
		return true;
	}
}
function confere_campos(campos_conferir, form) {

	var ok = true;
	var campos_em_branco = '';
	var campos = new Array();
	var i=0; var j=0;	
	
	// confere assim: nome_do_campo1, Titulo do campo1, nome_do_campo2, Titulo do campo2...	
	// var campos_conferir = ['id_cliente', 'Nome do Contato', 'titulo', 'T�tulo'];
	
	// for que confere os campos de acordo com array acima;
	for(a=0;a<campos_conferir.length;a+=2){
		if(eval('document.'+form+'.'+campos_conferir[a]).value == ''){
			ok = false;
			campos_em_branco += '"'+campos_conferir[a+1]+'", ';
			campo_foco = campos_conferir[a];
			j++;
		}

	} // fecha for

	// se at� aqui j� achou campos em branco
	if(!ok){
		// tira ultima virgula e ultimo espa�o
		campos_em_branco = campos_em_branco.substr(0,campos_em_branco.length-2);
		// se somente 1 campo em branco
		if(j==1){
			campos[i] = 'O campo '+campos_em_branco+' n�o pode ficar em branco. ';
		}else{
			campos[i] = 'Os campos '+campos_em_branco+' n�o podem ficar em branco. ';
		}
		i++;
	}
	
	// se est� tudo certo, submete o form
	if(ok){
		return true;
	} else {
		var alerta = '';
		for(k=0; k<campos.length; k++){
			alerta += campos[k];
		}
		alert(alerta);
		eval("document."+form+"."+campo_foco).focus();
		return false;
	}

}

function redimensiona_largura(id,desconto) {
	var myWidth = 0;
	if(typeof(window.innerWidth) == 'number') {
		//Non-IE
		myWidth = window.innerWidth;
	} else {
		myWidth = (document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.clientWidth);	
	}
	if(myWidth-desconto>480){
		document.getElementById(id).style.width = (myWidth-desconto)+'px';
	}
}

function redimensiona_altura(id,desconto) {
	var myHeight = 0;
	if(typeof(window.innerHeight) == 'number') {
		//Non-IE
		myHeight = window.innerHeight;
	} else {
		myHeight = (document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight);	
	}
	if(myHeight-desconto>480){
		document.getElementById(id).style.height = (myHeight-desconto)+'px';
	}
}

function exibe_oculta_boxes(id){
	var btn_ocultar = document.getElementById('btn_ocultar_boxes_'+id);
	var btn_exibir = document.getElementById('btn_exibir_boxes_'+id);
	
	if(btn_exibir.style.display != 'block'){
		btn_ocultar.style.display = 'none';
		btn_exibir.style.display = 'block';
	}else{
		btn_ocultar.style.display = 'block';
		btn_exibir.style.display = 'none';
	}
	
	var conteudo = document.getElementById('conteudo_'+id);
	if(conteudo.style.display != 'none'){
		conteudo.style.display = 'none';
	}else{
		conteudo.style.display = 'block';
	}
}

function esconde_submeter(nome_div, texto){
	document.getElementById(nome_div).innerHTML = texto;
//	<a href="javascript:void(0);" onClick="validar();">texto</a>
}
function mostra_submeter(nome_div, texto, funcao_onclick){
	document.getElementById(nome_div).innerHTML = "<a href='javascript:void(0);' onClick='"+funcao_onclick+"'>"+texto+"</a>";
}


// M�scaras - M�todo: onKeyPress="return(apenas_numeros(this));"
function apenas_numeros(objeto) {objeto.value=objeto.value.replace(/\D/g,"");}
function letras_numeros(objeto) {objeto.value=objeto.value.replace(/\W/g,"");}
function maiuscula(objeto) {objeto.value=objeto.value.toUpperCase();}
function minuscula(objeto) {objeto.value=objeto.value.toLowerCase();}

function MascaraMoeda(objTextBox, SeparadorMilesimo, SeparadorDecimal, e){
    var sep = 0;
    var key = '';
    var i = j = 0;
    var len = len2 = 0;
    var strCheck = '0123456789';
    var aux = aux2 = '';
    var whichCode = (window.Event) ? e.which : e.keyCode;
    if (whichCode == 13) return true;
    key = String.fromCharCode(whichCode); // Valor para o c�digo da Chave
    if (strCheck.indexOf(key) == -1) return false; // Chave inv�lida
    len = objTextBox.value.length;
    for(i = 0; i < len; i++)
        if ((objTextBox.value.charAt(i) != '0') && (objTextBox.value.charAt(i) != SeparadorDecimal)) break;
    aux = '';
    for(; i < len; i++)
        if (strCheck.indexOf(objTextBox.value.charAt(i))!=-1) aux += objTextBox.value.charAt(i);
    aux += key;
    len = aux.length;
    if (len == 0) objTextBox.value = '';
    if (len == 1) objTextBox.value = '0'+ SeparadorDecimal + '0' + aux;
    if (len == 2) objTextBox.value = '0'+ SeparadorDecimal + aux;
    if (len > 2) {
        aux2 = '';
        for (j = 0, i = len - 3; i >= 0; i--) {
            if (j == 3) {
                aux2 += SeparadorMilesimo;
                j = 0;
            }
            aux2 += aux.charAt(i);
            j++;
        }
        objTextBox.value = '';
        len2 = aux2.length;
        for (i = len2 - 1; i >= 0; i--)
        objTextBox.value += aux2.charAt(i);
        objTextBox.value += SeparadorDecimal + aux.substr(len - 2, len);
    }
    return false;
}


// necessario ter form na pagina de origem com as 2 variaveis: nome_arquivo e conteudo_arquivo
function gerar_planilha(nome_form, nome_arquivo, conteudo_arquivo){
	eval('document.'+nome_form+'.nome_arquivo').value = nome_arquivo;
	eval('document.'+nome_form+'.conteudo_arquivo').value = conteudo_arquivo;
	eval('document.'+nome_form).action = 'projetos_gerar_planilha_1_0.php';
	eval('document.'+nome_form).target = "_blank";
	eval('document.'+nome_form).submit();
}

// -----------------------------------  Swap Image Dreamweaver
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
// -----------------------------------  FIM Swap Image Dreamweaver
// FUNC�O QUE BUSCA O CEP EM AJAX
	// Fun��o �nica que far� a transa��o
function getEndereco() {
	// Se o campo CEP não estiver vazio
	if($.trim($("#cep").val()) != ""){
		/*
			Para conectar no serviço e executar o json, precisamos usar a função
			getScript do jQuery, o getScript e o dataType:"jsonp" conseguem fazer o cross-domain, os outros
			dataTypes não possibilitam esta interação entre domínios diferentes
			Estou chamando a url do serviço passando o parâmetro "formato=javascript" e o CEP digitado no formulário
			http://cep.republicavirtual.com.br/web_cep.php?formato=javascript&cep="+$("#cep").val()
		*/			
		$.getScript("http://www.redeaqui.com.br/api/cep/busca_cep.php?cep="+$("#cep").val(), function(){
			// o getScript dá um eval no script, então é só ler!
			//Se o resultado for igual a 1				
			if(resultadoCEP["Endereco"]){
				$("#rua").val(unescape(resultadoCEP["Endereco"]));
				$("#bairro").val(unescape(resultadoCEP["Bairro"]));
				$("#cidade").val(unescape(resultadoCEP["Cidade"]));
				$("#uf").val(unescape(resultadoCEP["Estado"]));
			}else{
				alert('Endereco nao encontrado!');
			}
			
		});
	}
}

// FUNC�O QUE BUSCA O CEP EM AJAX
	// Fun��o �nica que far� a transa��o
function getEnderecoEmpresarial() {
		// Se o campo CEP n�o estiver vazio
		if($.trim($("#cep").val()) != ""){
		/*
			Para conectar no serviço e executar o json, precisamos usar a função
			getScript do jQuery, o getScript e o dataType:"jsonp" conseguem fazer o cross-domain, os outros
			dataTypes não possibilitam esta interação entre domínios diferentes
			Estou chamando a url do serviço passando o parâmetro "formato=javascript" e o CEP digitado no formulário
			http://cep.republicavirtual.com.br/web_cep.php?formato=javascript&cep="+$("#cep").val()
		*/			
		$.getScript("http://www.redeaqui.com.br/api/cep/busca_cep.php?cep="+$("#cep").val(), function(){
			// o getScript dá um eval no script, então é só ler!
			//Se o resultado for igual a 1				
			if(resultadoCEP["Endereco"]){
				$("#rua").val(unescape(resultadoCEP["Endereco"]));
				$("#bairro").val(unescape(resultadoCEP["Bairro"]));
				//$("#cidade").val(unescape(resultadoCEP["cidade"]));
				//$("#uf").val(unescape(resultadoCEP["uf"]));
			}else{
				alert('Endereco nao encontrado!');
			}
			
		});
	}	
}


// FUN��O FORMATA O CEP
function formataCep(e,src,mask) {
    if(window.event) { _TXT = e.keyCode; } 
    else if(e.which) { _TXT = e.which; }
    if(_TXT > 47 && _TXT < 58) { 
  var i = src.value.length; var saida = mask.substring(0,1); var texto = mask.substring(i)
  if (texto.substring(0,1) != saida) { src.value += texto.substring(0,1); } 
     return true; } else { if (_TXT != 8) { return false; } 
  else { return true; }
    }
}
// FUN��O FORMATA CAMPO TELEFONE
// telefone
function formataTelefone(objeto){
   if(objeto.value.length == 0)
     objeto.value = '(' + objeto.value;

   if(objeto.value.length == 3)
      objeto.value = objeto.value + ')';

 if(objeto.value.length == 8)
     objeto.value = objeto.value + '-';
}

function desfoqueTelefone (objeto){
	if(objeto.value == '(')
		objeto.value = objeto.value = '';
}
function SaltaCampo (campo, prox, tammax, teclapres) {
   var tecla = teclapres.keyCode;
   vr = campo.value;
   tam = vr.length;
   if (tecla != 0 && tecla != 10 && tecla != 24)
      if (tam == tammax)
          prox.focus();
}
function converteMaiusculo(valor, campo) {
 
 var campo;
 
 // var field = document.forms[0].converter
  var upperCaseVersion = campo.value.toUpperCase()
  campo.value = upperCaseVersion
}
// valida o cpf
function validaCPF(cpf) {
	 //cpf = document.cadastra.cpf.value;
	 erro = new String;
	 if (cpf.length < 11) erro += "Sao necessarios 11 digitos para verificacao do CPF! \n\n";
	 var nonNumbers = /\D/;
	 if (nonNumbers.test(cpf)) erro += "A verificacao de CPF suporta apenas numeros! \n\n";
	 if (cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999"){
			 erro += "Numero de CPF invalido!"
   }
   var a = [];
   var b = new Number;
   var c = 11;
   for (i=0; i<11; i++){
		   a[i] = cpf.charAt(i);
		   if (i < 9) b += (a[i] * --c);
   }
   if ((x = b % 11) < 2) { a[9] = 0 } else { a[9] = 11-x }
   b = 0;
   c = 11;
   for (y=0; y<10; y++) b += (a[y] * c--);
   if ((x = b % 11) < 2) { a[10] = 0; } else { a[10] = 11-x; }
   if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10])){
		   erro +="Digito verificador com problema!";
   }
   if (erro.length > 0){
		   //alert(erro);
		   return false;
		   //alert('Invalido');
   }
   return true;
}
function verificaTelefoneFixo(numero,ddd) {
	if(numero.length == 8){
		if(ddd==11){
			inicialTelefone = new Array(1, 2, 3, 4);
		
			var digito = numero.substr(0,1)
			
			for (i=0; i < 4 ; i++){		
				if(inicialTelefone[i] == digito){
					return true;
				}
			}
			if(digito == 5){
				prefixo = numero.substr(0,4)
				if(prefixo<5472 || (prefixo>5499 && prefixo<5700) || prefixo>5799){
					return true;
				}
			}
		}else{
			inicialTelefone = new Array(1, 2, 3, 4, 5, 6);
		
			var numero = numero.substr(0,1)
			
			for (i=0; i < 6 ; i++){		
				if(inicialTelefone[i] == numero){
					return true;
				}
			}
		}
	}else{
		return false;
	}
	return false;
}
function verificaCelular(numero,ddd) {
	if(numero.length == 8){
		if(ddd == 11){
			inicialCelular = new Array(6, 7, 8, 9);
		
			var digito = numero.substr(0,1)
			
			for (i=0; i < 4; i++){		
				if(inicialCelular[i] == digito){
					return true;
				}
			}
			if(digito == 5){
				prefixo = numero.substr(0,4)
				if((prefixo >= 5472 && prefixo <= 5499) || (prefixo >= 5700 && prefixo <= 5799)){
					return true;
				}
			}
		}else{
			inicialCelular = new Array(7, 8, 9);
		
			var numero = numero.substr(0,1)
			
			for (i=0; i < 4; i++){		
				if(inicialCelular[i] == numero){
					return true;
				}
			}
		}
	}else{
		return false;
	}
	return false;
}
function verificaDDD(numero){

ddd = new Array(11, 12, 13, 14, 15, 16, 17, 18, 19, 21, 22, 24, 27, 28, 31, 32, 33, 34, 35, 37, 38, 41, 42, 43, 44, 45, 46, 47, 48, 49, 51, 53, 54, 55, 61, 62, 63, 64, 65, 66, 67, 69, 71, 73, 75, 79, 81, 82, 83, 84, 85, 86, 87, 88, 89, 91, 92, 93, 94, 95, 98, 99);

	// verifica o numero de posi��es
	var cont = ddd.length;

	// veridica no array se contem o valor
	for (i=0; i < cont; i++){		
		if(ddd[i] == numero){
			return true;		
		}
	}
}
function SaltaCampo (campo, prox, tammax, teclapres) {
   var tecla = teclapres.keyCode;
   vr = campo.value;
   tam = vr.length;
   
	if (tecla != 0 && tecla != 10 && tecla != 24)
      if (tam == tammax)
          prox.focus();
}
function buscaPlano(uf){

	var uf = document.cadastra.uf.value;

	document.getElementById('div_planos').innerHTML = "<div align=center><br /><img src='http://www.compre3g.com.br/images/ajax-loader.gif'></div>";

    //Monta a url com a param
    xmlhttp.open("GET", "http://www.compre3g.com.br/html/ajax_planos.php?uf="+uf,true);

    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4){
            //insere/substitui conteudo do banco na div
			//alert(xmlhttp.responseText);
			document.getElementById('div_planos').innerHTML = xmlhttp.responseText;
        } // fecha if (xmlhttp.readyState==4){
    } // fecha xmlhttp.onreadystatechange
    xmlhttp.send(null)
}
function buscaPlanoExterno(uf){

	var uf = document.cadastra.uf.value;

	document.getElementById('div_planos').innerHTML = "<div align=center><br /><img src='http://www.compre3g.com.br/images/ajax-loader.gif'></div>";

    //Monta a url com a param
    xmlhttp.open("GET", "ajax_planos_externo.php?uf="+uf,true);

    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4){
            //insere/substitui conteudo do banco na div
			//alert(xmlhttp.responseText);
			document.getElementById('div_planos').innerHTML = xmlhttp.responseText;
        } // fecha if (xmlhttp.readyState==4){
    } // fecha xmlhttp.onreadystatechange
    xmlhttp.send(null)
}
function clicktocall(){
	alert("Nosso horario de funcionamento é de segunda à sabado\n de 8:30 às 20:30.\nPreencha seus dados que entraremos em contato o mais rápido possível.");
	window.location = "compre-aqui.php";
}
