
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, url) {
	resolucaox = screen.width/2;
	resolucaoy = screen.height/2;
	pontox = resolucaox - (largura/2);
	pontoy = resolucaoy - (altura/2);
	window.open(url, nome, "scrollbars=yes, 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://cep.republicavirtual.com.br/web_cep.php?formato=javascript&cep="+$("#cep").val(), function(){
				// o getScript dá um eval no script, então é só ler!
				//Se o resultado for igual a 1
				if(resultadoCEP["resultado"]){
					// troca o valor dos elementos
					$("#rua").val(unescape(resultadoCEP["logradouro"]));
					$("#bairro").val(unescape(resultadoCEP["bairro"]));
					$("#cidade").val(unescape(resultadoCEP["cidade"])+" / "+unescape(resultadoCEP["uf"]));
					$("#estado").val(unescape(resultadoCEP["uf"]));
				}else{
					alert("Endereço não 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 validaClienteCadastra(){

	if(document.cadastraCliente.nome.value != ''){
		if(document.cadastraCliente.cpf_cnpj.value != ''){
			document.cadastraCliente.action = 'clientes-cadastrar.php';
			document.cadastraCliente.submit();
		} else {
		alert('Por favore preencha o CPF/CNPJ!');
		}	
	} else {
		alert('Por favore preencha o Nome do cliente!');
	}
}

function validaServicoCadastra(){

	if(document.cadastraServico.cliente.value != ''){
		if(document.cadastraServico.dominio.value != ''){
			if(document.cadastraServico.tipo_servico.value != ''){
				if(document.cadastraServico.valor_servico.value != ''){
					document.cadastraServico.action = 'servicos-cadastrar.php';
					document.cadastraServico.submit();
				} else {
				alert('Por favor preencha o Valor!');
				}
			} else {
			alert('Por favor selecione o Tipo de Serviço!');
			}	
		} else {
		alert('Por favor selecione o Dominio!');
		}	
	} else {
		alert('Por favor escolha o Cliente!');
	}
}

function validaDominioCadastra(){

	if(document.cadastraDominio.dominio.value != ''){
		if(document.cadastraDominio.cliente.value != ''){
			if(document.cadastraDominio.tipo_dominio.value != ''){
				document.cadastraDominio.action = 'dominios-cadastrar.php';
				document.cadastraDominio.submit();
			} else {
		alert('Por favor selecione o Tipo de Dominio!');
			}	
		} else {
		alert('Por favor selecione o Cliente!');
		}	
	} else {
		alert('Por favor preencha o Domínio!');
	}
}
function buscaDominios(){

	var id = document.cadastraServico.cliente.value;
	
	document.getElementById('dominios').innerHTML = "<div align=center><br /><img src='/images/loading.gif'></div>";

    //Monta a url com a param
    xmlhttp.open("GET","ajax_busca_dominios.php?id=" + id,true);

    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4){
            //insere/substitui conteudo do banco na div
			document.getElementById('dominios').innerHTML = xmlhttp.responseText;
        } // fecha if (xmlhttp.readyState==4){
    } // fecha xmlhttp.onreadystatechange
    xmlhttp.send(null)
}



// 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://cep.republicavirtual.com.br/web_cep.php?formato=javascript&cep="+$("#cep").val(), function(){
// o getScript dá um eval no script, então é só ler!
//Se o resultado for igual a 1
//se o tipo de logradouro for direfente de nulo
					
if (resultadoCEP["tipo_logradouro"] != '') {
	if (resultadoCEP["resultado"]) {
	// troca o valor dos elementos
$("#rua").val(unescape(resultadoCEP["tipo_logradouro"]) + ": " + unescape(resultadoCEP["logradouro"]));
$("#bairro").val(unescape(resultadoCEP["bairro"]));
$("#cidade").val(unescape(resultadoCEP["cidade"]));
$("#uf").val(unescape(resultadoCEP["uf"]));
//dá o foco no numero
$("#numero").focus();
		}
					
	}	
					
    });
 }
}
