// JavaScript Document
// Validação de campo vazio. Param: campo, nome do campo para exibição
var valorCookie, idiomaAtual;
valorCookie = getCookie("JBN");


if( valorCookie.indexOf("idioma=English") != -1 ) { // Inglês selecionado
	idiomaAtual = "English";
	preencher = "At least one of the fields must be filled.";
	txt_branco = "The field ";
	txt_branco2 = " must be filled in.";
	txt_emailvalido = "The e-mail must be a valid email.";
	txt_telefone="Telephone number invalid\nEnter the area code and phone number.\nExample: (11) 1234-5678"
	txt_data = "Date format is invalid!";
	txt_numero1 = "The field ";
	txt_numero2 = " must contain numbers only.";
	txt_url1 = "The field ";
	txt_url2 = " does not contain a valid address ";
	txt_cnpj="does not contain a valid address "
	txt_horario1="The time "
	txt_horario2=" is invalid"
	
	txt_cartaoCredito = "Credit cart number is invalid";
	txt_codSeguranca = "Security code must contain 3 characters";
	txt_dataValidadeCartao = "Validity date is invalid.";
	txt_temCerteza = "Are you sure?";
}  else {
		idiomaAtual = "Portugues";
			
		txt_branco = "O campo ";
		txt_branco2 = " deve ser preenchido.";
		txt_emailvalido = "O e-mail deve ser um endereço de e-mail válido.";
		txt_telefone="Número de telefone inválido\nEntre com o DDD e o número do telefone.\nExemplo: (11) 1234-5678"
		txt_data = "O formato da data é invalido!";
		txt_numero1 = "O campo ";
		txt_numero2 = " deve conter apenas números.";
		txt_url1 = "O campo ";
		txt_url2 = " não contém um endereço válido.";
		txt_cnpj="CNPJ/CPF inválido"
		txt_horario1="O horário"
		txt_horario2=" é inválido"
		preencher = "Pelos menos um dos campos deve ser preenchido.";
		txt_cartaoCredito = "O número do cartão de crédito é inválido";
		txt_codSeguranca = "O código de segurança deve ter 3 caracteres";
		txt_dataValidadeCartao = "Data de validade inválida."
		txt_temCerteza = "Tem certeza?";	
	
}

function validaBuscaEdicoes() {
	if( !validaBranco2("volume") && !validaBranco2("numero") && !validaBranco2("pagina") ){
		alert(preencher);
		return false;	
	}

	if( !validaNumero("volume") )
		return false;
	if( !validaNumero("numero") )
		return false;
	if( !validaNumero("pagina") )
		return false;
				
	return true;
}

function validaBranco( campo, nome ){
	campo = document.getElementById( campo );

	if( trim( campo.value ) == "" ) {
		if( nome != null )
			alert( txt_branco + nome.toUpperCase() + txt_branco2 );
		else
			alert( txt_branco + campo.name.toUpperCase() + txt_branco2 );
		
		campo.focus();
		return false;
	}
	return true;
}

// Validação de campo vazio sem exibir alert
function validaBranco2( campo ){
	campo = document.getElementById( campo );

	if( trim( campo.value ) == "" ) 
		return false;
	return true;
}

//Validação de email
function validaEmail( campo )
{
	campoform = document.getElementById( campo );
	return validaEmailPorCampo( campoform );
}

function validaEmailPorCampo( campo ){
	campoform = campo;
	email = campoform.value;

    if ( email )
	{
		p = email.indexOf('@');
		pont = email.indexOf('.');
		if ( p < 1 || p == (email.length - 1) || pont < 1 || pont == (email.length - 1) )
		{
				alert (txt_emailvalido);
	    		campoform.value = '';
	    		campoform.focus();
				return false;
		}
	} else {
		alert (txt_emailvalido);
  		campoform.value = '';
	    campoform.focus();
		return false;
	}
	return true;
}

//Validação de Telefone
function validaTelefone( campoPar ) {
	campo = document.getElementById( campoPar );
	var valor='';
	var digito = false;
	a = campo.value;

	if ( a != "" ) {
		num = a.length;
		for (f=0;f<num;f++)
		{
			if (parseInt(a.substr(f,1)) || a.substr(f,1)=='0') 
			if ((a.substr(f,1) != '0') || digito) valor = valor + '' + a.substr(f,1);
			if (parseInt(a.substr(f,1)) && a.substr(f,1) != '0') digito = true;
		};
		num = valor.length;
		if (num < 9 || num > 10)
		{
			alert (txt_telefone);
			campo.focus();
			return false;
		}
		else
		{
			if (num == 9) valor = '(' + valor.substr(0, 2) + ') ' + valor.substr(num-7, 3) + '-' + valor.substr(num-4, 4);
			if (num == 10) valor = '(' + valor.substr(0, 2) + ') ' + valor.substr(num-8, 4) + '-' + valor.substr(num-4, 4);
			campo.value = valor;
		}
	}
	else{
		alert (txt_telefone);
		campo.focus();
		return false;
	}
	return true;
}

// validação de data
function validaData( campo ){
	var data = document.getElementById(campo);

	hoje = new Date();
    anoAtual = hoje.getFullYear();
   	barras = data.value.split("/");
    if (barras.length == 3){
		dia = barras[0];
        mes = barras[1];
   	    ano = barras[2];
        resultado = (!isNaN(dia) && (dia > 0) && (dia < 32)) && (!isNaN(mes) && (mes > 0) && (mes < 13)) && (!isNaN(ano) && (ano.length == 4) );
   	    if (!resultado) {
			alert("O formato da data é invalido!");
            data.focus();
            return false;
		}
	}
	else {
		alert("O formato da data é invalido!");
		data.focus();
        return false;
   	}
	return true;
}

//validação de números
function validaNumero( campo ){
	var numero = document.getElementById( campo );
	var numeroValor = numero.value.replace( ",",".");
	
	if ( isNaN( numeroValor ) ){
		alert( txt_numero1 + numero.name.toUpperCase() + txt_numero2 );
		numero.focus();
		return false;
	}
	return true;
}

// comparação de 2 datas
function comparaData( data1, data2 ){
	var data1 = document.getElementById( data1 );
	var data2 = document.getElementById( data2 );
		
	var dataArray1 = data1.value.split( "/" );
	var dataArray2 = data2.value.split( "/" );
	
	var dData1 = new Date( dataArray1[2], dataArray1[1] - 1, dataArray1[0] );
	var dData2 = new Date( dataArray2[2], dataArray2[1] - 1, dataArray2[0] );

	if ( dData1.getTime() > dData2.getTime() )
		return 1;
	else if ( dData1.getTime() < dData2.getTime() )
		return -1;
	else
		return 0;
}

// Valida um URL
function validaURL( campo ){
	campo = document.getElementById( campo );

	if( campo.value.substr(0, 7) != "http://" || campo.value.length <= 12 ){
		alert( "O campo " + campo.name.toUpperCase() + " não contém um endereço válido." );
		campo.focus();
		return false;
	}
	return true;
}

// Validação de CPF
function validaCPF( campoform ) {
	num_cpf = '';
	campo = campoform.value;
	if (campo == "00000000000" || campo == "11111111111" || campo == "22222222222" || campo == "33333333333" || campo == "44444444444" || campo == "55555555555" || campo == "66666666666" || campo == "77777777777"  || campo == "88888888888"  || campo == "99999999999"){
		return false;
	}
	if (campo == "000.000.000-00" || campo == "111.111.111-11" || campo == "222.222.222-22" || campo == "333.333.333-33" || campo == "444.444.444-44" || campo == "555.555.555-55" || campo == "666.666.666-66" || campo == "777.777.777-77"  || campo == "888.888.888-88"  || campo == "999.999.999-99"){
		return false;
	}
	if (!campo) return true;
	for (i=0;i<campo.length;i++) {
			resposta=campo.charAt(i) ;
			num = parseFloat(resposta);
			if (resposta==''+num) num_cpf=num_cpf+resposta; 
		}

	if (num_cpf.length == 11) {
		soma = 0;
		for (i=0; i < 9; i ++) soma += parseInt(num_cpf.charAt(i)) * (10 - i);
		resto = 11 - (soma % 11);
		if (resto == 10 || resto == 11)	resto = 0;
		soma = 0;
		for (i = 0; i < 10; i ++) soma += parseInt(num_cpf.charAt(i)) * (11 - i);
		resto2 = 11 - (soma % 11);
		if (resto2 == 10 || resto2 == 11) resto2 = 0;
		if ((resto != parseInt(num_cpf.charAt(9))) || (resto2 != parseInt(num_cpf.charAt(10)))) {
			return false;
		}
		else {
			campoform.value= num_cpf.substring(0,3) + '.' + num_cpf.substring(3,6) + '.'
			+ num_cpf.substring(6,9) + '-' + num_cpf.substring(9,11);
			return true;
		}
	}
	else {
		return false;
	}	
}

function trim(txt){  
	var retirar = ' ';
	var retorno = '';

	for(i=0;i<txt.length;i++){  
		if(retirar.indexOf(txt.substr(i,1)) == -1){  
			retorno += txt.substr(i,1);
		}
	}  
	return retorno;
}

//Função para validar CNPJ
function validaCNPJ( campoform ){
	num_cpf = '';
	campo = campoform.value;

	if (!campo) return true;
	
	for (i=0;i<campo.length;i++)
		{
		resposta=campo.charAt(i) ;
		num = parseFloat(resposta);
		if (resposta==''+num) num_cpf=num_cpf+resposta; 
		}

	if (num_cpf.length == 14)
		{
		d1= 0;
		d4= 0;
		xx= 1;
		for (nCount = 0;nCount< num_cpf.length-2;nCount++)
			{
			if (xx < 5) fator= 6 - xx; else fator= 14 - xx;
			d1 = d1 + num_cpf.charAt(nCount) * fator;
			if (xx < 6) fator = 7 - xx; else fator = 15 - xx;
			d4 = d4 + num_cpf.charAt(nCount) * fator;
	    	xx = xx+1;
			}
		resto = d1%11;
		if (resto < 2) digito1 = 0; else digito1 = 11 - resto;
		d4 = d4 + 2 * digito1;
		resto = d4%11;
		if (resto < 2) digito2 = 0; else digito2 = 11 - resto;
		Check = digito1+''+digito2;
        if (Check != num_cpf.substring(num_cpf.length-2,num_cpf.length))
			{
			alert ('- CNPJ inválido. \nEntre com o CNPJ correto.');
    		campoform.value = '';
    		campoform.focus();
			return false;
			}
		else 
			{
			campoform.value= num_cpf.substring(0,2)
			+ '.' + num_cpf.substring(2,5) + '.' + num_cpf.substring(5,8) + '/' + num_cpf.substring(8,12)
			+ '-' + num_cpf.substring(12,14);
			return true;
			};
		}
	else
		{
		alert ('- CNPJ inválido. \nEntre com o CNPJ correto.');
    	campoform.value = '';
    	campoform.focus();
		return false;
		}
}

//Exibe ou esconde pelo Id
function mostraDados( pri ) {
  var element = document.getElementById(pri);

  if (element.style.display == 'none') {
    element.style.display = '';
  }
  else {
    element.style.display = 'none'
  }
}

// Validação de hora
function validaHora( nomeCampo ){
	var reTime = /^([0-1]\d|2[0-3]):[0-5]\d:[0-5]\d$/;
	
	var campoTempo = document.getElementById(nomeCampo);
	var valorCampoTempo = campoTempo.value;
	
	eval("reTime = reTime");
	
	if( !reTime.test(valorCampoTempo) && validaBranco2(nomeCampo) ){
		alert("O horário " + valorCampoTempo + " é inválido.");
		campoTempo.focus();
		return false;
	} 
	return true;
}

function getCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    } else {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1) {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

//retorna o elemento
function $(nomeElemento) {
	return document.getElementById(nomeElemento);
}

function isIE8() {
	if(navigator.appVersion.indexOf("MSIE 8.0") >= 0)
		return true;
	return false;
}

// Copiar tabela e colocar no campo "conteudoTabela"
function exportarExcel() {
	document.getElementById("conteudoTabela").value = document.getElementById("tabelaExpandida").innerHTML;	
}