/*========================================================*/
/* Funções Javascript revisadas por Julio 10/08/2001		 */				
/*========================================================*/

	function Item(name, subItens){
		this.name = name;
		this.subItens = subItens;
	}

	function subItem(value, name){
		this.name = name;
		this.value = value;
	}

	function writeCaptionRadio(cod, nomeArray){
		var str='';
		if (nomeArray != null){
			for(i=0; i < nomeArray.length; i++){
				if (nomeArray[i].value == cod){
					str = nomeArray[i].name;
					return str;
				}
			}			
		}
		return str;
	}

	function writeCaption(cod, nomelist){
		var str = '', i;
		campolist = eval('document.form.'+nomelist);
		if (campolist != null){
			for (i = 0; i < campolist.length; i++){
				if (campolist.options[i].value == cod){
					str = campolist.options[i].text;
				}
			}
		}
		return str;
	}

	


/*==========================================================*/
/* Dada uma string a fumção Trim retira espaços em branco 	*/
/* à esquerda e à direita da string													*/
/*==========================================================*/
	function trim(str){
		var firstIndex = 0;
		var lastIndex = str.length-1;
		var retorno = '';
		while (str.charAt(firstIndex) == ' '){
			firstIndex++;
		}
		while (str.charAt(lastIndex) == ' '){
			lastIndex--;
		}
		lastIndex++;
		retorno = str.substring(firstIndex,lastIndex);
		return retorno;
	}

/*================================================================================*/
/* Dado	o um campo list e um campo hidden																					*/
/* Ao clicar no	list box define	o valor	do campo hidden	do formulario de remocao	*/
/*================================================================================*/
function checa_list(campolist1, campohidden1){
	campohidden1.value = campolist1.options[campolist1.selectedIndex].value;
	return;
}

/*================================================================================*/
/* Passados um campo list e o título do campo list																*/
/* Verifica se algum item está selecionado e alerta o usuário											*/
/* Se estiver selecionado avisa	o usuario que a	operação não podera ser	desfeita	*/
/*================================================================================*/
function checa_remove(nomecampolist1, msgvazia, msgselecionado){
	campolist1 = eval('document.form_list.'+nomecampolist1);
	if (campolist1 == null){
		alert(msgvazia);
		return false;
	}
	if (campolist1.selectedIndex == -1) {
		alert(msgselecionado);
		return false;
	}
	if (!confirm("Tem certeza que deseja apagar o item selecionado?")) {
		return false;
	}
	return true;
}

/*=====================================================*/
/* Passados nome e descricao de	um campo texto				 */
/* Verifica se o campo esta vazio e alerta o usuario	 */
/*=====================================================*/
function checa_insere(campotext1, msgvazia, msgexiste, nomecampolist1){
	if ((campotext1.value == "") || (campotext1.value == " ")){
		alert(msgvazia);
		campotext1.focus();
		return false;
	}	
	campolist1 = eval('document.form_list.'+nomecampolist1);
	if (campolist1 != null){
		for (var i = 0; i < campolist1.length; i++){
			if (iguais(campotext1.value, campolist1.options[i].text)){
				alert(msgexiste);
				campotext1.value = '' ;
				campotext1.focus();
				return false;
			}
		}
	}
	return true;
}
/*========================================================================*/
/* Passados duas strings essa função campara com CaseSensitive as duas		*/
/* e o retorno é bem trivial :o)																					*/
/*========================================================================*/
function iguais(str1, str2){
	if (str1.toUpperCase() == str2.toUpperCase()){
		return true;
	}
	return false;
}

/*=======================================================================*/
/* Função cujo objetivo é trocar o valor do listbox nas paginas nas quais*/
/* existem tabelas relacionadas														 */
/*=======================================================================*/
function troca(nomecampolist1, nomecampolist2, valorcampolist2){
	var campolist1 = eval('document.form_list.'+nomecampolist1);

	if (campolist1 != null){		
		var campolist2 = eval('document.form_insere.'+nomecampolist2);
		while (campolist1.length > 0){
			campolist1.options[0] = null;
		}	
		var j = 0;

		if (valorcampolist2 == ''){
			indiceselecionado = 0;
		}else{
			for(i = 0; i < campolist2.length; i++){
				if( campolist2.options[i].value == valorcampolist2 ){
					indiceselecionado = i;
				}
			}
		}

		for(i = 0; i < Objeto[indiceselecionado].subItens.length; i++){
			if(Objeto[indiceselecionado].subItens[i].name != ''){
				temp = new Option (Objeto[indiceselecionado].subItens[i].name,Objeto[indiceselecionado].subItens[i].value);
				campolist1.options[j] = temp;
				j++;
			}else{
				campolist1.length = 0;
			}
		}

		campolist2.selectedIndex = indiceselecionado;
		var campolist2_remove = eval('document.form_remove.'+nomecampolist2);
		campolist2_remove.value = campolist2.options[campolist2.selectedIndex].value;

	}
	return;
}


// Obtencao de dados do browser do visitante
var isNav = false, isIE = false, Versao="0.00";
var browserOK = false;
var pics;
browserOK = true;
pics = new Array();
var objCount = 0; 

AppName = navigator.appName;
AppVersion = navigator.appVersion;

if ( AppName.indexOf("Netscape") != -1 ) 
{
  isNav = true;
  Versao = AppVersion.substring(0, 4);
  document.captureEvents(Event.KEYDOWN);  
}
else if ( AppName.indexOf("Microsoft") != -1 ) {
   isIE = true;
   Versao = AppVersion.substring((AppVersion.indexOf("E")+1), (AppVersion.indexOf("E")+6));
}

NUMVER = parseFloat(Versao)
if ( NUMVER >= 5) {
   Versao = "5";
} else if ( NUMVER >= 4 ) {
   Versao = "4";
} else if ( NUMVER >= 3 ) {
   Versao = "3";
} else Versao = "2";


// Funcao para saltar de um campo para o proximo automaticamente
function salta(campo_atual, event, tamanho_maximo, campo_proximo)
{
  var tecla;
  var vr;

  if (isNav)
    tecla = event.which;
  else
    tecla = event.keyCode;
  vr = campo_atual.value;
  tam = vr.length;
  if (tam >= tamanho_maximo && tecla >= 48)
    campo_proximo.focus();
}


//Verifica e-mails válidos

function check_email (emailStr) {
var emailPat=/^(.+)@(.+)$/
var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
var validChars="\[^\\s" + specialChars + "\]"
var quotedUser="(\"[^\"]*\")"
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
var atom=validChars + '+'
var word="(" + atom + "|" + quotedUser + ")"
var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")

var matchArray=emailStr.match(emailPat)
if (matchArray==null) {
	alert("Favor inserir um e-mail válido.");
	return false;
}
var user=matchArray[1]
var domain=matchArray[2]

if (user.match(userPat)==null) {
    alert("Favor inserir um e-mail válido.");
    return false;
}

var IPArray=domain.match(ipDomainPat)
if (IPArray!=null) {
	  for (var i=1;i<=4;i++) {
	    if (IPArray[i]>255) {
	        alert("Favor inserir um e-mail válido.");
		return false;
	    }
    }
    return true;
}

var domainArray=domain.match(domainPat)
if (domainArray==null) {
	alert("Favor inserir um e-mail válido.");
    return false;
}

var atomPat=new RegExp(atom,"g")
var domArr=domain.match(atomPat)
var len=domArr.length
if (domArr[domArr.length-1].length<2 || 
    domArr[domArr.length-1].length>3) {
   alert("Favor inserir um e-mail válido.");
   return false;
}

if (len<2) {
   var errStr="Favor inserir um e-mail válido.";
   alert(errStr);
   return false;
}


return true;
}

/*====================================================================*/
/* Essa função recebe uma string na forma de data e retorna 'true' ou */
/* 'false' de acordo com a validade da data.                       		*/
/*====================================================================*/
function testDate(str){
	var dia, mes, ano;
	tempArray = str.split('/');
	tempArray[0] = chopLeftZero(tempArray[0]);
	tempArray[1] = chopLeftZero(tempArray[1]);
	tempArray[2] = chopLeftZero(tempArray[2]);
	dia = parseInt(tempArray[0]);
	mes = parseInt(tempArray[1]);
	ano = parseInt(tempArray[2]);

	if (ano < 1900){return false;}
	if (mes < 1 || mes > 12){return false;}
	if (dia < 1 || dia > 31){return false;}
	if (dia > 29 && mes == 2){return false;}
	if (dia == 29 && mes == 2){
		if(ano % 4 != 0){return false;}
	}
	if (dia == 31 && mes < 8 ){
		if (mes % 2 == 0){return false;}
	}
	if (dia == 31 && mes >= 8 ){
		if (mes % 2 == 1){return false;}
	}
	return true;
}

/*==========================================================================*/
/* Dado uma string essa função diz se a mesma é uma seqüêcia numérica válida*/
/*==========================================================================*/
function isNumber(str){
	var i;
	if (str == null || str == "" || str == " "){return false;}
	for (i=0; i<str.length; i++){
		if(!isDigit(str.charAt(i))){return false;}
	}
	return true;
}

/*=======================================================*/
/* Dado uma string essa função diz se a mesma está vazia */
/*=======================================================*/
function isEmpty(str){
	if (str == null || str == "" || str == " "){return true;}
	return false;
}

/*==================================================================*/
/* Essa função diz se a data é valida ou não.												*/
/* O parâmetro 'obr' é fundamental na decisão da validação da data	*/
/*==================================================================*/
function checkDate(campohidden, titledata, campotextdia, campotextmes, campotextano, obr){
	tempDate = concatDate(campotextdia, campotextmes, campotextano);
	if (tempDate == '-1'){
		// alert('O valor da '+titledata+' está incorreto.');
		alert(titledata+' inválida.');
		campotextdia.focus();
		return false;
	}
	if (tempDate == "" && obr == 0){return true;}
	if (tempDate != "" && testDate(tempDate)){
		campohidden.value = tempDate;
		return true;
	}else{
		// alert('O valor da '+titledata+' está incorreto.');
		alert(titledata+' inválida.');
		campotextdia.focus();
		return false;
	}
}

/*=====================================================*/
/* Função que recebe uma string e retira os caracteres */
/* iniciais enquanto forem o caracter zero '0'				 */
/*=====================================================*/
function chopLeftZero(str){
	var i = 0;
	while (str.charAt(i) == 0){
		i++;
	}
	str = str.slice(i, str.length+1);
	return str;
}

/*===============================================*/
/* Função de concatenação dos values do listbox  */
/*===============================================*/
function concatena(campolist1){
	var i, str = '';
	for(i = 0; i < campolist1.length; i++){
		str = str + campolist1.options[i].value +' ';
	}
	if (!isBlank(str)){
		str = trim(str);
	}else{
		str = '';
	}
	return str;
}

/*===================================================================================*/
/* Dada uma string essa função diz se ela é constituída apenas por espaços em branco */
/*===================================================================================*/
function isBlank(str){
	for (i=0; i<str.length; i++){
		if (str.charAt(i)!= ' '){return false;}
	}
	return true;
}

/*======================================================================*/
/* Dados campos dia, mês e ano se os 3 campos possuírem valores			*/
/* numéricos válidos os valores serão concatenados na forma de data		*/
/* e retornados, do contrário uma string vazia será retornada	se todos */
/* os campos estiverem vazios.														*/
/* Se algum dos campos não for vazio e não for um numérico válido o 	 	*/
/* código de retorno é (-1). 															*/
/*======================================================================*/
function concatDate(dia, mes, ano){
	var strDate = '';
	if (isNumber(dia.value) && isNumber(mes.value) && isNumber(ano.value)){
		strDate = dia.value+'/'+mes.value+'/'+ano.value;
		return strDate;
	}		
	if (!isEmpty(dia.value) || !isEmpty(mes.value) || !isEmpty(ano.value)){
	  strDate = '-1';
 		return strDate;
	}

return strDate;

}

/*==============================================*/
/* Função de troca de valores entre ListBoxes	*/
/*==============================================*/
function move(boxOrigem, boxDestino) {
	var ArrayOrigem = new Array();
	var ArrayDestino = new Array();
	var ArrayTemp = new Array();
	var i;

	for (i = 0; i < boxDestino.length; i++) {
		if (boxDestino.options[i].value != ""){
			//ArrayTemp[boxDestino.options[i].text] = boxDestino.options[i].value;
			ArrayDestino[i] = boxDestino.options[i].text+'|'+boxDestino.options[i].value;
		}
	}

	var OrigemLength = 0;
	var DestinoLength = ArrayDestino.length;

	for(i = 0; i < boxOrigem.length; i++) {
		//ArrayTemp[boxOrigem.options[i].text] = boxOrigem.options[i].value;
		if (boxOrigem.options[i].selected && boxOrigem.options[i].value != "") {
			ArrayDestino[DestinoLength] = boxOrigem.options[i].text+'|'+boxOrigem.options[i].value;
			DestinoLength++;
		}
		else {
			ArrayOrigem[OrigemLength] = boxOrigem.options[i].text+'|'+boxOrigem.options[i].value;
			OrigemLength++;
   }
	}

	ArrayDestino.sort();
	ArrayOrigem.sort();
	boxOrigem.length = 0;
	boxDestino.length = 0;

	var c;

	for(c = 0; c < ArrayOrigem.length; c++) {
		var no = new Option();
		/*
		no.value = ArrayTemp[ArrayOrigem[c]];
		no.text = ArrayOrigem[c];
		*/
		var strtemp = ArrayOrigem[c].split('|'); //*
		no.value = strtemp[1];
		no.text = strtemp[0];
		boxOrigem[c] = no;
	}
	
	for(c = 0; c < ArrayDestino.length; c++) {
		var no = new Option();
		/*
		no.value = ArrayTemp[ArrayDestino[c]];
		no.text = ArrayDestino[c];
		*/
		var strtemp = ArrayDestino[c].split('|'); //*
		no.value = strtemp[1];
		no.text = strtemp[0];
		boxDestino[c] = no;
  }
	if (boxOrigem.length > 0){
		boxOrigem.selectedIndex = 0;
	}
}

/*==========================================================================*/
/* Dado um caracter essa função diz se o mesmo é um dígito numérico válido	*/
/*==========================================================================*/
function isDigit(ch){
	var i;
	if (ch == null || ch == "" || ch == " "){return false;}
	for (i=0; i<=9; i++){
		if (ch == i){return true;}
	}
	return false;
}

/*==========================================================================*/
/* Checa se o CPF e valido                                                  */
/*==========================================================================*/

function check_cpf (StrCPF)
{
 x = 0;
 soma = 0;
 dig1 = 0;
 dig2 = 0;
 texto = "";
 StrCPF1="";
 len = StrCPF.length; 
 x = len -1;
  for (var i=0; i <= len - 3; i++)
  {
   y = StrCPF.substring(i,i+1);
   soma = soma + ( y * x);
   x = x - 1;
   texto = texto + y;
  }
  dig1 = 11 - (soma % 11);
  if (dig1 == 10) dig1=0 ;
  if (dig1 == 11) dig1=0 ;
  StrCPF1 = StrCPF.substring(0,len - 2) + dig1 ;
  x = 11; soma=0;
  for (var i=0; i <= len - 2; i++)
  {
   soma = soma + (StrCPF1.substring(i,i+1) * x);
   x = x - 1;
  }
  dig2= 11 - (soma % 11);
  if (dig2 == 10) dig2=0;
  if (dig2 == 11) dig2=0;
  if ((dig1 + "" + dig2) == StrCPF.substring(len,len-2))
  {
   return true;
  }
  alert ("Número do CPF inválido.");
  return false;
 }


function check_CNPJ (StrCNPJ)
 {
      var varFirstChr = StrCNPJ.charAt(0);
      var vlMult,vlControle,s1, s2 = "";
      var i,j,vlDgito,vlSoma = 0;
	  var vaCharCNPJ = false;
      for ( var i=0; i<=13; i++ ) {

        var c = StrCNPJ.charAt(i);
        if( ! (c>="0")&&(c<="9") )
        {
      alert("Número do CNPJ inválido.");
      return false; }
        if( c!=varFirstChr ) { vaCharCNPJ = true; }
      }
      if( ! vaCharCNPJ ) { 

      alert("Número do CNPJ inválido.");
      return false;
      }


      s1 = StrCNPJ.substring(0,12);
      s2 = StrCNPJ.substring(12,15);
      vlMult = "543298765432";
      vlControle = "";
      for ( j=1; j<3; j++ ) {

       vlSoma = 0;
       for ( i=0; i<12; i++ )
        { vlSoma += eval( s1.charAt(i) )* eval( vlMult.charAt(i) );}
         if( j == 2 ){ vlSoma += (2 * vlDgito); }
         vlDgito = ((vlSoma*10) % 11);
         if( vlDgito == 10 ){ vlDgito = 0; }
         vlControle = vlControle + vlDgito;
         vlMult = "654329876543";
      }
      if( vlControle != s2 ) {
      alert("Número do CNPJ inválido.");
      return false;
      }
      else {
      return true;
      }                          


}

function validaCPF(){
	var StrData = document.form_cpf.cod_usuario.value;
	if (check_cpf(StrData) == false) {
		return false;
	}
	return true;
}

function validaCNPJ(){
	var StrData = document.form_CNPJ.cod_usuario.value;

	if (check_CNPJ(StrData) == false) {
		return false;
	}
	return true;
}