function vai_url(theURL) { //v2.0
  window.self.location=theURL;
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

function browser() {
var agt=navigator.userAgent.toLowerCase();
if (agt.indexOf("opera") != -1) return 'Opera';
if (agt.indexOf("staroffice") != -1) return 'Star Office';
if (agt.indexOf("webtv") != -1) return 'WebTV';
if (agt.indexOf("beonex") != -1) return 'Beonex';
if (agt.indexOf("chimera") != -1) return 'Chimera';
if (agt.indexOf("netpositive") != -1) return 'NetPositive';
if (agt.indexOf("phoenix") != -1) return 'Phoenix';
if (agt.indexOf("firefox") != -1) return 'Firefox';
if (agt.indexOf("safari") != -1) return 'Safari';
if (agt.indexOf("skipstone") != -1) return 'SkipStone';
if (agt.indexOf("msie") != -1) return 'Internet Explorer';
if (agt.indexOf("netscape") != -1) return 'Netscape';
if (agt.indexOf("mozilla/5.0") != -1) return 'Mozilla';
if (agt.indexOf('\/') != -1) {
if (agt.substr(0,agt.indexOf('\/')) != 'mozilla') {
return navigator.userAgent.substr(0,agt.indexOf('\/'));}
else return 'Netscape';} else if (agt.indexOf(' ') != -1)
return navigator.userAgent.substr(0,agt.indexOf(' '));
else return navigator.userAgent;
}

function MM_goToURL(url) { //v3.0
eval("window.location='"+url+"'");
}
//-->

//FUNCÃO PARA FECHAR AS JANELAS ABERTAS DENTRO DO SISTEMA
function fecha_popup(){
var $ = window.parent.$; 
var jQuery = window.parent.jQuery; 
$().ready(function() { 
$.unblockUI({ fadeOut: 200 });
}); 
window.parent.location.reload();

}

//FUNCÃO PARA ABRIR AS JANELAS USADAS PARA O CADASTRO DO SISTEMA
function abre_janela(largura,altura,url){
var brow = browser();
if ((brow == 'Firefox')|| (brow == 'Mozilla')){
altura  = (altura*1.25) ;
largura = (largura*1.10) ;
	document.getElementById("geral").src=url;
} else {
	window.geral.location.href= url; 
}

	document.getElementById("geral").height = altura;
	document.getElementById("geral").width = largura;
	//document.getElementById("geral").scrolling="auto";
		
		$().ready(function() {
		$.blockUI({ message: $('#campos'),
		css: {
              top:  ($(window).height() - altura) /2 + 'px',
			  left: ($(window).width() - largura) /2 + 'px',
			  width: largura,
			  height: altura			
			}
		 }); 
		}); 
	return false;		
}

//FUNCÃO UTILIZADA PARA ABRIR PROMPT DE EXLUSÃO DE REGISTROS
function excluir(codigo,nome,mensagem,endereco,tipo){
		    $.blockUI({ message: $('#mensagem'),
			width: 330
			}); 
 			document.getElementById("mens").value=mensagem;
        $('#todos').click(function() { 
            // update the block message 
			if (endereco!='digivoice.php?acao=restart'){
            $.blockUI({ message: "<h1>Exluindo o "+tipo+" : "+nome+"</h1>"}); 
			} else {
			$.blockUI({ message: "<h1>REINICIANDO O SERVIÇO!</h1>"}); 
			}
						
            $.ajax({ 
                url: endereco, 
                cache: false, 
                complete: function() { 
                  window.parent.location.reload();
                    $.unblockUI(); 
                } 
            }); 
        }); 		
 
        $('#cancela').click(function() { 
            $.unblockUI(); 
            return false; 
        }); 
 }
//FUNCÃO DE ALERTA DE EXISTENCIA DE REGISTROS NA INCLUSÃO
function alerta_existe(mensagem){
		    $.blockUI({ message: $('#alerta'),
			css: { width: '275px',
					left: '20%',
					top: '20%'
			 }
			}); 
			window.mens2.value=mensagem;
 
        $('#volta').click(function() { 
            $.unblockUI();
			history.back(); 
            return false; 
        }); 
 }

var HttpReq = null;
var dest_combo = null;

//FUNCÃO PARA TRATAR A POPULAÇÃO DAS COMBOBOX
//GRUPO COM 4 FUNÇÕES
 function ajaxComboBox(url,comboBox,origem){
  	 dest_combo = comboBox;
	 orig_combo = origem;
    var indice = document.getElementById(orig_combo).selectedIndex;
    var sigla = document.getElementById(orig_combo).options[indice].getAttribute('value');
    url = url;
    if (document.getElementById) { //Verifica se o Browser suporta DHTML.
        if (window.XMLHttpRequest) {
            HttpReq = new XMLHttpRequest();
            HttpReq.onreadystatechange = XMLHttpRequestChange;
            HttpReq.open("GET", url, true);
            HttpReq.send(null);
        } else if (window.ActiveXObject) {
            HttpReq = new ActiveXObject("Microsoft.XMLHTTP");
            if (HttpReq) {
                HttpReq.onreadystatechange = XMLHttpRequestChange;
                HttpReq.open("GET", url, false);
                HttpReq.send();
            }
        }
    }
 }

 function ajaxComboBox2(url,comboBox,origem){
  	 dest_combo = comboBox;
	 orig_combo = origem;
    var indice = document.getElementById(orig_combo).selectedIndex;
    var sigla = document.getElementById(orig_combo).options[indice].getAttribute('value');
    url = url;
    if (document.getElementById) { //Verifica se o Browser suporta DHTML.
        if (window.XMLHttpRequest) {
            HttpReq = new XMLHttpRequest();
            HttpReq.onreadystatechange = XMLHttpRequestChange;
            HttpReq.open("GET", url, false);
            HttpReq.send(null);
        } else if (window.ActiveXObject) {
            HttpReq = new ActiveXObject("Microsoft.XMLHTTP");
            if (HttpReq) {
                HttpReq.onreadystatechange = XMLHttpRequestChange;
                HttpReq.open("GET", url, false);
                HttpReq.send();
            }
        }
    }
 }



 function XMLHttpRequestChange() {
    if (HttpReq.readyState == 4 && HttpReq.status == 200){
        var result = HttpReq.responseXML;
        var cidades = result.getElementsByTagName("nome");
		var padrao = result.getElementsByTagName("valor1");
        document.getElementById(dest_combo).innerHTML = "";
		var valor1 = padrao[0].getAttribute("id");
        for (var i = 0; i < cidades.length; i++) {
            new_opcao = create_opcao(cidades[i]);
            document.getElementById(dest_combo).appendChild(new_opcao);
			if (valor1 == document.getElementById(dest_combo).options[i].value){
			document.getElementById(dest_combo).options[i].selected = true;
			}
        }
    }
 }

 function create_opcao(cidade) {  
    var new_opcao = document.createElement("option"); 
    var texto = document.createTextNode(cidade.childNodes[0].data); 	
    new_opcao.setAttribute("value",cidade.getAttribute("id")); 
    new_opcao.appendChild(texto); //Adiciona o texto a OPTION.
    return new_opcao; // Retorna a nova OPTION.
 }


function marca_selecao(origem,destino){
 var j =  document.getElementById(destino).length;
	for (var i = 0; i < j; i++) { 
		if (origem == document.getElementById(destino).options[i].value){
		 document.getElementById(destino).options[i].selected = true;
		}
	}
}

function BlockKeybord()
{
if((event.keyCode < 48) || (event.keyCode > 57))
{
event.returnValue = false;
}
}

function troca(str,strsai,strentra)
{
while(str.indexOf(strsai)>-1)
{
str = str.replace(strsai,strentra);
}
return str;
}

function FormataMoeda(campo,tammax,teclapres,caracter)
{
if(teclapres == null || teclapres == "undefined")
{
var tecla = -1;
}
else
{
var tecla = teclapres.keyCode;
}

if(caracter == null || caracter == "undefined")
{
caracter = ".";
}

vr = campo.value;
if(caracter != "")
{
vr = troca(vr,caracter,"");
}
vr = troca(vr,"/","");
vr = troca(vr,",","");
vr = troca(vr,".","");

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

if(tecla == 8)
{
tam = tam - 1;
}
}
if(tecla == -1 || tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105)
{
if(tam <= 2)
{ 
campo.value = vr;
}
if((tam > 2) && (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) + caracter + vr.substr(tam - 5, 3) + ',' + vr.substr(tam - 2, tam);
}
if((tam >= 9) && (tam <= 11))
{
campo.value = vr.substr(0, tam - 8) + caracter + vr.substr(tam - 8, 3) + caracter + vr.substr(tam - 5, 3) + ',' + vr.substr(tam - 2, tam);
}
if((tam >= 12) && (tam <= 14))
{
campo.value = vr.substr(0, tam - 11) + caracter + vr.substr(tam - 11, 3) + caracter + vr.substr(tam - 8, 3) + caracter + vr.substr(tam - 5, 3) + ',' + vr.substr(tam - 2, tam);
}
if((tam >= 15) && (tam <= 17))
{
campo.value = vr.substr(0, tam - 14) + caracter + vr.substr(tam - 14, 3) + caracter + vr.substr(tam - 11, 3) + caracter + vr.substr(tam - 8, 3) + caracter + vr.substr(tam - 5, 3) + ',' + vr.substr(tam - 2, tam);
}
}
}

function maskKeyPress(objEvent) 
{
var iKeyCode; 
iKeyCode = objEvent.keyCode; 
if(iKeyCode>=48 && iKeyCode<=57) return true;
return false;
}
//Fim da Função FormataReais -->

function soma_orcado(valor){
document.form1.valor_orcado.value='';	
valor2=0;
for (i=0;i<document.form1.elements.length;i++) {
      if(document.form1.elements[i].type == "text") {
	  nome = document.form1.elements[i].name;
	  if (nome.substr(0,6)=="orcado"){
		vcampo = document.form1.elements[i].value;
		vcampo = vcampo.replace(',','');
		vcampo = vcampo.replace('.','');		
		valor2 = valor2+parseFloat(vcampo);
		}
 	  }
}
document.form1.valor_orcado.value=valor2;	 
}

function formatCurrency(num) {
num = num.toString().replace(/\$|\,/g,'');
if(isNaN(num))
num = "0";
sign = (num == (num = Math.abs(num)));
num = Math.floor(num*100+0.50000000001);
cents = num%100;
num = Math.floor(num/100).toString();
if(cents<10)
cents = "0" + cents;
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
num = num.substring(0,num.length-(4*i+3))+'.'+
num.substring(num.length-(4*i+3));
return (((sign)?'':'-') + '' + num + ',' + cents);
}

function por_valor(tipo){
document.form1.total.value='';
valor=document.form1.meta_geral.value;
por = document.form1.desafio_geral.value;

if (tipo=='P'){
total= ((parseFloat(valor.replace('.',''))*parseFloat(por.replace(',','.')))/100)+parseFloat(valor.replace('.',''));
total = total.toFixed(2);
} else {
total = ((parseFloat(por.replace('.',''))-parseFloat(valor.replace('.','')))*100)/parseFloat(valor.replace('.',''));
total = total.toFixed(2);
}
document.form1.total.value = formatCurrency(total);
}


function por_valor2(tipo){
document.form1.total2.value='';
valor=document.form1.meta.value;
por = document.form1.desafio.value;

if (tipo=='P'){
total= ((parseFloat(valor.replace('.',''))*parseFloat(por.replace(',','.')))/100)+parseFloat(valor.replace('.',''));
total = total.toFixed(2);
} else {
total = ((parseFloat(por.replace('.',''))-parseFloat(valor.replace('.','')))*100)/parseFloat(valor.replace('.',''));
total = total.toFixed(2);
}
document.form1.total2.value = formatCurrency(total);
}

function formatar(src, mask){
  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);
  }
}
function validaCPF(valor){
   var cpf = valor;
   var filtro = /^\d{3}.\d{3}.\d{3}-\d{2}$/i;
   if(!filtro.test(cpf)){
     window.alert("CPF inválido. Tente novamente.");
	 return false;
   }
   
   cpf = remove(cpf, ".");
   cpf = remove(cpf, "-");
    
   if(cpf.length != 11 || cpf == "00000000000" || cpf == "11111111111" ||
	  cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" ||
	  cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" ||
	  cpf == "88888888888" || cpf == "99999999999"){
	  window.alert("CPF inválido. Tente novamente.");
	  return false;
   }

   soma = 0;
   for(i = 0; i < 9; i++)
   	 soma += parseInt(cpf.charAt(i)) * (10 - i);
   resto = 11 - (soma % 11);
   if(resto == 10 || resto == 11)
	 resto = 0;
   if(resto != parseInt(cpf.charAt(9))){
	 window.alert("CPF inválido. Tente novamente.");
	 return false;
   }
   soma = 0;
   for(i = 0; i < 10; i ++)
	 soma += parseInt(cpf.charAt(i)) * (11 - i);
   resto = 11 - (soma % 11);
   if(resto == 10 || resto == 11)
	 resto = 0;
   if(resto != parseInt(cpf.charAt(10))){
     window.alert("CPF inválido. Tente novamente.");
	 return false;
   }
   return true;
 }
 
 function remove(str, sub) {
   i = str.indexOf(sub);
   r = "";
   if (i == -1) return str;
   r += str.substring(0,i) + remove(str.substring(i + sub.length), sub);
   return r;
 }

function validaCNPJ(valor) {
                 CNPJ = valor;
                 erro = new String;
                 if (CNPJ.length < 18) erro += "É necessario preencher corretamente o número do CNPJ! \n\n"; 
                 if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")){
                 if (erro.length == 0) erro += "É necessário preencher corretamente o número do CNPJ! \n\n";
                 }
                 //substituir os caracteres que não são números
               if(document.layers && parseInt(navigator.appVersion) == 4){
                       x = CNPJ.substring(0,2);
                       x += CNPJ. substring (3,6);
                       x += CNPJ. substring (7,10);
                       x += CNPJ. substring (11,15);
                       x += CNPJ. substring (16,18);
                       CNPJ = x; 
               } else {
                       CNPJ = CNPJ. replace (".","");
                       CNPJ = CNPJ. replace (".","");
                       CNPJ = CNPJ. replace ("-","");
                       CNPJ = CNPJ. replace ("/","");
               }
               var nonNumbers = /\D/;
               if (nonNumbers.test(CNPJ)) erro += "A verificação de CNPJ suporta apenas números! \n\n"; 
               var a = [];
               var b = new Number;
               var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
               for (i=0; i<12; i++){
                       a[i] = CNPJ.charAt(i);
                       b += a[i] * c[i+1];
 }
               if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }
               b = 0;
               for (y=0; y<13; y++) {
                       b += (a[y] * c[y]); 
               }
               if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; }
               if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])){
                       erro +="Dígito verificador com problema!";
               }
               if (erro.length > 0){
                       alert(erro);
                       return false;
               } else {
                       alert("CNPJ valido!");
               }
               return true;
       }

	var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
	document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));

	try {
		var pageTracker = _gat._getTracker("UA-15273015-1");
		pageTracker._trackPageview();
	} catch(err) {}


  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-15571292-2']);
  _gaq.push(['_setDomainName', '.com.br']);
  _gaq.push(['_trackPageview']);
  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

