function redireciona(url) {
	window.location = url;
}

function exclui(url) {
	if (confirm("Se deseja realmente excluir este registro clique em Ok")) {
		window.location = url;
	}
}

function browser(){
	var userAgent = ' ';
	userAgent = navigator.userAgent;
	var agent = ' ';
	if(userAgent.indexOf("Firefox") > -1){
		agent =  'firefox';
	}else if(userAgent.indexOf("MSIE 6") > -1 ){
		agent = 'IE6';
	}else if(userAgent.indexOf("MSIE 7") > -1 ){
		agent = 'IE7';
	}else if(userAgent.indexOf("MSIE 8") > -1){
		agent = 'IE8';
	}
	return agent;
}
function Popup(url,width,heigth){
	var pop = window.open("about:blank","_blank","width=10,height=100,top=0,left=0");
	if (null == pop || true == pop.closed){
	  h = 1;
	  alert('Atenção!!\n\nAnti-Popup detectado!!\n\nDesabilite o seu anti-Popup primeiro!!');
	} else {
	  h = 0;
	  pop.close();
	  if(!(width && heigth)){
		  window.open(url,'_blank','directories=no','location=no','menubar=yes','status=no','titlebar=no','toolbar=no');
	  }else{
		  window.open(url,'_blank','width='+width+',height='+heigth,'directories=no','location=no','menubar=yes','status=no','titlebar=no','toolbar=no');
	  }
	}	
}
function valida_dataNascimento(data){
	if(data.value.length<8){
		return false; 
	}else{
		var dataNasc = data.value;
		var dataHoje = new Date();
		var anoAtual = dataHoje.getYear();
		if(anoAtual<200){
			anoAtual = anoAtual + 1900;
		}
		var mesAtual = dataHoje.getMonth();
		var diaAtual = dataHoje.getDate();
		var bisexto  = true;
		try{
			if(dataNasc.length==8){
				diaNasc = dataNasc.substring(0,2);
				mesNasc = dataNasc.substring(2,4);
				anoNasc = dataNasc.substring(4,8);
				dataNasc = diaNasc+"/"+mesNasc+"/"+anoNasc;
			}else if(dataNasc.length==10){
				diaNasc = dataNasc.substring(0,2);
				mesNasc = dataNasc.substring(3,5);
				anoNasc = dataNasc.substring(6,10);
				if(dataNasc.substring(2,3)!="/"||dataNasc.substring(5,6)!="/"){
					return false; 
				}  
			}
			if((anoNasc>1900)&&(anoNasc<=anoAtual)&&(mesNasc>0)&&(mesNasc<13)){

				bisexto=((anoNasc%4==0)&&((anoNasc%100!=0)||(anoNasc%400==0)))
				var diasMes; 
				diasMes = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
				if(bisexto){
					diasMes[1] = 29;
				}

				if(diaNasc>0&&diaNasc<=diasMes[mesNasc-1]){
					var dtnasct = ""+anoNasc+mesNasc+diaNasc; 
					var dtatual = ""+anoAtual+(mesAtual+1)+diaAtual; 

					if(dtnasct<dtatual){
						data.value = dataNasc
					}else{
						return false; 
					}
					return true; 
				}else{
					return false; 
				}
			}else{
				return false; 
			}
		}catch(e){
			return false; 
		}
	}
}
function VerificaData(digData) 
{
    var bissexto = 0;
    var data = digData; 
    var tam = data.length;
    if (tam == 10) 
    {
        var dia = data.substr(0,2)
        var mes = data.substr(3,2)
        var ano = data.substr(6,4)
        if (ano > 2006 && ano < 2020)
        {
            switch (mes) 
            {
                case '01':
                case '03':
                case '05':
                case '07':
                case '08':
                case '10':
                case '12':
                    if  (dia <= 31) 
                    {
                        return true;
                    }
                    break
                
                case '04':        
                case '06':
                case '09':
                case '11':
                    if  (dia <= 30) 
                    {
                        return true;
                    }
                    break
                case '02':
                    /* Validando ano Bissexto / fevereiro / dia */ 
                    if ((ano % 4 == 0) || (ano % 100 == 0) || (ano % 400 == 0)) 
                    { 
                        bissexto = 1; 
                    } 
                    if ((bissexto == 1) && (dia <= 29)) 
                    { 
                        return true;                 
                    } 
                    if ((bissexto != 1) && (dia <= 28)) 
                    { 
                        return true; 
                    }            
                    break                        
            }
        }
    }    
    return false;
}
function validaCPF(cpf){
	if(cpf!=null){
		var tamanho = (cpf*1)+'';   
		cpf = Complete(cpf,11,"0","E")
		if(tamanho.length<4)return false;
		var nonNumbers = /\D/;
		if (cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999"){
			return false;
		}
		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])||(cpf.charAt(10)=="")){
			return false;
		}
		return true;
	}else{
		return false;
	}    
}
function vcnpj( c ) {

	var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais, cnpj = c.value.replace(/\D+/g, '');
	digitos_iguais = 1;
	if (cnpj.length != 14) 
	{
		alert('CNPJ inválido');
		c.focus();
		return false;
	}

	for (i = 0; i < cnpj.length - 1; i++)
		if (cnpj.charAt(i) != cnpj.charAt(i + 1))
		{
			digitos_iguais = 0;
			break;
		}
	if (!digitos_iguais)
	{
		tamanho = cnpj.length - 2
		numeros = cnpj.substring(0,tamanho);
		digitos = cnpj.substring(tamanho);
		soma = 0;
		pos = tamanho - 7;
		for (i = tamanho; i >= 1; i--)
		{
			soma += numeros.charAt(tamanho - i) * pos--;
			if (pos < 2)
				pos = 9;
		}
		resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
		if (resultado != digitos.charAt(0))
		{
			alert('CNPJ inválido');
			c.focus();
			return false;
		}

		tamanho = tamanho + 1;
		numeros = cnpj.substring(0,tamanho);
		soma = 0;
		pos = tamanho - 7;
		for (i = tamanho; i >= 1; i--)
		{
			soma += numeros.charAt(tamanho - i) * pos--;
			if (pos < 2)
				pos = 9;
		}
		resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
		if (resultado != digitos.charAt(1)){
			alert('CNPJ inválido');
			c.focus();
			return false;
		}
		else {
			// alert('CNPJ  OK !');
			return true;
		}
	}
	else{
		alert('CNPJ inválido');
		c.focus();
		return false;
	}
} 
function Complete(texto,tamNecessario,caractere,lado){
	//texto
	//tamNecessario - tamho que o texto devera ter no fim
	//  caractere 
	//  lado  E esquedo D Direito
	var falta = tamNecessario-texto.length;
	var textoAnexar ="";
	for (y=0; y<falta; y++){textoAnexar=textoAnexar+caractere;}
	if(lado=="D")
		texto=texto+textoAnexar
		else
			texto=textoAnexar+texto;
	return texto;
}
function nomeSobrenome(nome){ 
	var nomeValido= false;
	var carac = 0;
	var char32 = false;
	for(x=0;x<nome.length;x++){
		carac = nome.charCodeAt(x,x+1);
		if(char32&&carac>0&&carac!=32){
			nomeValido = true;
			break;
		}  
		if (x!=0&&carac==32){
			char32 = true;
		}else if (x==0&&carac==32){
			nomeValido = false;
			break;
		}
	}
	return nomeValido;
}

function trim(str){
	if(!str || typeof str != 'string')
		return null;
	return str.replace(/^[\s]+/,'').replace(/[\s]+$/,'').replace(/[\s]{2,}/,' ');
}


//função para digitar menos
function getId(Id){
	return document.getElementById(Id);	
}

//adiciona um option no select
function addOption(Id, val)
{
	var elOptNew = document.createElement('option');
	elOptNew.text = val;
	elOptNew.value = val;
	var elSel = document.getElementById(Id);

	try {
		elSel.add(elOptNew, null); // standards compliant; doesn't work in IE
	}
	catch(ex) {
		elSel.add(elOptNew); // IE only
	}
}
function addOption2(Id, val,txt)
{
	var elOptNew = document.createElement('option');
	elOptNew.text = txt;
	elOptNew.value = val;
	var elSel = document.getElementById(Id);
	try {
		elSel.add(elOptNew, null); // standards compliant; doesn't work in IE
	}
	catch(ex) {
		elSel.add(elOptNew); // IE only
	}
}
//inicio script para formatar valor (money)

//formata um valor
function FormataValor(campo,tammax,teclapres) { 
	//uso: 
	//< type="Text" name="fat_vr_bruto" maxlength="17" onKeyDown="FormataValor(this,17,event)"> 
	// FormataValor(123456) 

	if (typeof campo == "string" || typeof campo == "number") { 
		campo = getNumbers(campo); 
		return formatNumber(campo); 
	} else { 
		var vl = campo.value; 
		var tecla = teclapres.keyCode; 
		var vr = getNumbers(vl); 
		var tam = vr.length; 

		if ( tecla == 8 || tecla == 9 || tecla == 109 || (tecla >= 48 && tecla <= 57) || (tecla >= 96 && tecla <= 105) ) { 
			if(vl.indexOf("-")> -1){
				campo.value = vl.substr(0,1)+formatNumber(vr);
			}else{
				campo.value = formatNumber(vr);
			}
			return false; 
		} else { 
			return false; 
		} 
	} 
}

//retorna somente os números de uma string 
function getNumbers (arg0) { 
	var numbers = "0123456789"; 
	var resp = []; 
	arg0 = '' + arg0; 
	var size = arg0.length; 

	for (var i=0; i<size; i++) { 
		if (numbers.indexOf(arg0.charAt(i)) !== -1) { 
			resp.push(arg0.charAt(i)); 
		} 
	} 
	return resp.join(''); 
} 

//faz a formatação do número passado 
function formatNumber(arg0) { 
	if (arg0.length > 2) { 
		var rgx = /(\d+)(\d{3})/; 
		var start = arg0.substring(0, arg0.length - 2); 
		var end = ',' + arg0.charAt(arg0.length - 2) + '' + arg0.charAt(arg0.length - 1); 
		while (rgx.test(start)) { 
			start = start.replace(rgx, '$1.$2'); 
		}
		return start + end; 
	} else { 
		return arg0; 
	} 
} 

//fim script para formatar valor (money)


/**
 * Formata o Campo de acordo com a mascara informada.
 * Ex de uso: onkeyup="AplicaMascara('00:00:00', this);".
 * @param Mascara String que possui a mascara de formatação do campo.
 * @param elemento Campo que será formatado de acordo com a mascara, voce pode informar o id direto ou o próprio elemento usando o this.
 */
function AplicaMascara(Mascara, elemento){

	// Seta o elemento
	var elemento = (elemento) ? elemento : document.getElementById(elemento); 
	if(!elemento) return false;

	// Método que busca um determinado caractere ou string dentro de uma Array
	function in_array( oque, onde ){
		for(var i = 0 ; i <onde.length; i++){
			if(oque == onde[i]){
				return true;
			}
		}
		return false;
	}
	// Informa o array com todos os caracteres que podem ser considerados caracteres de mascara
	var SpecialChars = [':', '-', '.', '(',')', '/', ',', '_', ' '];
	var oValue = elemento.value;
	var novo_valor = '';
	for( i = 0 ; i <oValue.length; i++){
		//Recebe o caractere de mascara atual
		var nowMask = Mascara.charAt(i);
		//Recebe o caractere do campo atual
		var nowLetter = oValue.charAt(i);
		//Aplica a masca
		if(in_array(nowMask, SpecialChars) == true && nowLetter != nowMask){
			novo_valor +=  nowMask + '' + nowLetter;
		} else {
			novo_valor += nowLetter;
		}
		// Remove regras duplicadas
		var DuplicatedMasks = nowMask+''+nowMask;
		while (novo_valor.indexOf(DuplicatedMasks)>= 0) {
			novo_valor = novo_valor.replace(DuplicatedMasks, nowMask);
		}
	}
	// Retorna o valor do elemento com seu novo valor
	elemento.value = novo_valor;

} 
//----------------------------------------------------------//--------------------------------------------------------------//


/* @brief Converte uma string em formato moeda para float
      @param valor(string) - o valor em moeda
      @return valor(float) - o valor em float
 */
function converteMoedaFloat(valor){

	if(valor === ""){
		valor =  0;
	}else{
		valor = valor.replace(".","");
		valor = valor.replace(",",".");
		valor = parseFloat(valor);
	}
	return valor;

}

/*   @brief Converte um valor em formato float para uma string em formato moeda
      @param valor(float) - o valor float
      @return valor(string) - o valor em moeda
 */
function converteFloatMoeda(valor){
	var inteiro = null, decimal = null, c = null, j = null;
	var aux = new Array();
	valor = ""+valor;
	c = valor.indexOf(".",0);
	//encontrou o ponto na string
	if(c > 0){
		//separa as partes em inteiro e decimal
		inteiro = valor.substring(0,c);
		decimal = valor.substring(c+1,valor.length);
	}else{
		inteiro = valor;
	}

	//pega a parte inteiro de 3 em 3 partes
	for (j = inteiro.length, c = 0; j > 0; j-=3, c++){
		aux[c]=inteiro.substring(j-3,j);
	}

	//percorre a string acrescentando os pontos
	inteiro = "";
	for(c = aux.length-1; c >= 0; c--){
		inteiro += aux[c]+'.';
	}
	//retirando o ultimo ponto e finalizando a parte inteiro

	inteiro = inteiro.substring(0,inteiro.length-1);

	decimal = parseInt(decimal);
	if(isNaN(decimal)){
		decimal = "00";
	}else{
		decimal = ""+decimal;
		if(decimal.length === 1){
			decimal = decimal+"0";
		}
	}


	valor = "R$ "+inteiro+","+decimal;


	return valor;

}
