// ================================================================================================
// MÁSCARAS E VALIDAÇÃO ===========================================================================
// ================================================================================================

// E-mail										: validação
// Parâmetros								: src = value do objeto
function validaEmail(src) {
  emailReg = "^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[a-zA-Z]$"
  var regex = new RegExp(emailReg);
  return regex.test(src);
}

// Data 										: máscara dd/mm/aaaa
// Evento										: onKeyUp
// Parâmetros								: event = objeto event, obj = objeto origem
// Chamada									: onKeyUp="maskData(event, this);"
function maskData(event, obj) {
  tam = obj.value.length;
  if ((tam==2) || (tam==5)) obj.value = obj.value + "/";
}

// CEP 											: máscara nnnnn-nnn
// Evento										: OnKeyUp
// Parâmetros								: event = objeto event, obj = objeto origem
// Chamada									: onKeyUp="maskCEP(event, this);"
function maskCEP(event, obj) {
  tam = obj.value.length;
  if (tam==5) obj.value = obj.value + "-";
}

// Telefone									: máscara (nn) nnnn-nnnn
// Evento										: OnKeyUp
// Parâmetros								: event = objeto event, obj = objeto origem
// Chamada									: onKeyUp="maskTelefone(event, this);"
function maskTelefone(event, obj) {
  tam = obj.value.length;
  if (tam==1) obj.value = "(" + obj.value;
	if (tam==3) obj.value = obj.value + ") ";
	if (tam==9) obj.value = obj.value + "-";
}

// Dígitos (números)				: validação
// Evento										: OnKeyUp
// Parâmetros								: event = objeto event
// Chamada									: onKeyUp="digitos(event);"
function digitos(event){
	if (window.event) {
		// IE
		key = event.keyCode;
	} else if ( event.which ) {
		// netscape
		key = event.which;
	}
	if ( key != 8 || key != 13 || key < 48 || key > 57 )
		return ( ( ( key > 47 ) && ( key < 58 ) ) || ( key == 8 ) || ( key == 13 ) );
	return true;
}

// Valores reais						: validação
// Evento										: OnKeyUp
// Parâmetros								: event = objeto event, obj = objeto origem
// Chamada									: onKeyUp="valores(event, this);"
function valores(event,obj){
 	event.keyCode = (((event.keyCode < 48) || (event.keyCode > 57)) && ((event.keyCode != 44) || (obj.value.toString().indexOf(',')>=0)))?0:event.keyCode;
}

// Data											: validação
// Parâmetros								: Data = value do objeto
function isDate(Data){
  var dma = -1;
  var data = Array(3);
  var ch = Data.charAt(0);
  for(i=0; i < Data.length && (( ch >= '0' && ch <= '9' ) || ( ch == '/' && i != 0 ) ); ){
    data[++dma] = '';
    if(ch!='/' && i != 0) return false;
    if(i != 0 ) ch = Data.charAt(++i);
    if(ch=='0') ch = Data.charAt(++i);
    while( ch >= '0' && ch <= '9' ){
      data[dma] += ch;
      ch = Data.charAt(++i);
    }
  }
  if(ch!='') return false;
  if(data[0] == '' || isNaN(data[0]) || parseInt(data[0]) < 1) return false;
  if(data[1] == '' || isNaN(data[1]) || parseInt(data[1]) < 1 || parseInt(data[1]) > 12) return false;
  if(data[2] == '' || isNaN(data[2]) || ((parseInt(data[2]) < 0 || parseInt(data[2]) > 99 ) && (parseInt(data[2]) < 1900 || parseInt(data[2]) > 9999))) return false;
  if(data[2] < 50) data[2] = parseInt(data[2]) + 2000;
  else if(data[2] < 100) data[2] = parseInt(data[2]) + 1900;
  switch(parseInt(data[1])){
    case 2: { if(((parseInt(data[2])%4!=0 || (parseInt(data[2])%100==0 && parseInt(data[2])%400!=0)) && parseInt(data[0]) > 28) || parseInt(data[0]) > 29 ) return false; break; }
    case 4: case 6: case 9: case 11: { if(parseInt(data[0]) > 30) return false; break;}
    default: { if(parseInt(data[0]) > 31) return false;}
  }
  return true;
}

// CNPJ											: validação
// Parâmetros								: StrCGC = objeto origem
function validaCNPJ(StrCGC){
  var varFirstChr = StrCGC.charAt(0);
  var vlMult,vlControle,s1, s2 = "";
  var i,j,vlDgito,vlSoma = 0;
  for ( var i=0; i<=13; i++ ){
    var c = StrCGC.charAt(i);
    if(!(c>="0") && (c<="9")){
      return false;
    }
    if(c!=varFirstChr){
      vaCharCGC = true;
    }
  }
  if(!vaCharCGC){
    return false;
  }
  s1 = StrCGC.substring(0,12);
  s2 = StrCGC.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){
    return false;
  } else {
    return true;
  }
}

// CNPJ											: máscara nn.nnn.nnn/nnnn-nn
// Evento										: OnKeyUp
// Parâmetros								: event = objeto event, obj = objeto origem
// Chamada									: onKeyUp="maskCNPJ(event, this);"
function maskCNPJ(event, obj) {
  tam = obj.value.length;
  if (tam==2) obj.value = obj.value + ".";
  if (tam==6) obj.value = obj.value + ".";
  if (tam==10) obj.value = obj.value + "/";
  if (tam==15) obj.value = obj.value + "-";
}

// CNPJ											: remove máscara nn.nnn.nnn/nnnn-nn
// Parâmetros								: cnpj = value do objeto origem
// Chamada									: var cnpj = removeMaskCNPJ(objetoCNPJ.value);
function removeMaskCNPJ(cnpj) {
  var sCNPJ = cnpj;
  sCNPJ = sCNPJ.replace(/\./g,"");
	sCNPJ = sCNPJ.replace(/\//g,"");
	sCNPJ = sCNPJ.replace(/-/g,"");
	return sCNPJ;
}

// CPF											: máscara nnn.nnn.nnn-nn
// Parâmetros								: cnpj = value do objeto origem
// Chamada									: onKeyUp="maskCPF(event, this);"
function maskCPF(event, obj) {
  tam = obj.value.length;
  if (tam==3) obj.value = obj.value + ".";
  if (tam==7) obj.value = obj.value + ".";
  if (tam==11) obj.value = obj.value + "-";
}

// CPF											: validação
// Parâmetros								: StrCPF = objeto origem
function validaCPF(StrCPF){
	StrCPF = StrCPF.replace( ".", "" );
	StrCPF = StrCPF.replace( ".", "" );
	StrCPF = StrCPF.replace( "-", "" );
	
	var sStr = StrCPF.slice(0,1)
	var indStr = 1
	var trocou = false;
	
	while (indStr < StrCPF.length){
	if(sStr != StrCPF.substr(indStr,1)){
	trocou = true;
	}
	indStr++;
	}
	
	if (!trocou){
	return false
	}
	
	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;
	} else {
	  return false;
	}
}


// Arquivos									: validação
// Parâmetros								: frm = value do objeto origem
function validaArquivo(frm){
  if (frm.arquivo.value!='') {
    var arquivo = StrRev(frm.arquivo.value);
    arquivo = StrRev(arquivo.substring(0, arquivo.indexOf(".")));
		arquivo = arquivo.toLowerCase();
    if (arquivo!='jpg' && arquivo!='gif'){
      frm.reset();
      alert('Formato de arquivo inválido. Formatos válidos: jpg e gif.');
      return false;
    }
    else return true;
  }
}

// validaTipoArquivo				: verifica se o arquivo é de um tipo permitido
// Parâmetros								: obj = campo file, ext = array com tipos de arquivos válidos
function validaTipoArquivo(obj, ext){
  if (obj.value!='') {
    var arquivo = StrRev(obj.value);
    arquivo = StrRev(arquivo.substring(0, arquivo.indexOf(".")));
		arquivo = arquivo.toLowerCase();
    if (!inArray(ext, arquivo)){
      alert('Formato de arquivo inválido. Formatos válidos: '+ext.toString()+'.');
      return false;
    }
    else return true;
  }
}

// Checkboxes/Radios				: validação
// Parâmetros								: checkItem = nome do conjunto de checkboxes/radios
// Chamada									: selecionouCheck(nomeObjeto);
function selecionouCheck(checkItem){
  selecionou = false;
	if (isNaN(checkItem.length)){
	  selecionou = checkItem.checked;
	}
	else {
	  i = 0;
	  while ( (i <= (checkItem.length -1)) && (!selecionou) ){
    	selecionou = checkItem[i].checked;
    	i++;
	  }
	}
  return selecionou;
}

// ================================================================================================
// AUXILIARES =====================================================================================
// ================================================================================================

// String										: remonta a string de trás para frente
// Parâmetros								: str = value do objeto origem
function StrRev(str){
	var tmp = "";
  for (i=str.length-1; i >= 0; i--){
    tmp += str.charAt(i);
  }
  return tmp;
}

// Cor											: interface - altera a cor da linha selecionada
// Parâmetros								: obj = objeto de origem, i = indíce, chk = reservado
// Chamada									: onClick="cor(this, 1, null);"
var arCor = new Array();
function cor(obj, i, chk){
  if (arCor[i]=="1") {
    obj.style.backgroundColor = (i % 2 == 1)?"#F0F0F0":"#FFFFFF";
    arCor[i]="0";
  } else {
    obj.style.backgroundColor = '#fdfea9';
    arCor[i]="1";
  }
}

// Checkboxes								: interface - seleciona todos os checkboxes do conjunto
// Parâmetros								: obj = objeto de origem
// Chamada									: onClick="selectAll(nomeObjeto);"
function selectAll(obj){
	for (var i = 0 ; i < obj.options.length ; i++){
		obj.options[i].selected = true;
	}
}

function selectAllStr(form, obj){
  var f = document.getElementById(form);
	for (var i = 0 ; i < f.elements.length ; i++){
    if (f.elements[i].name==obj) {
		  var o = f.elements[i];
/*		  for (var j = 0; j < o.options.length; j++) {
			  o.options[j].selected = true;
			} */
		}
	}
}

// PopUp										: interface - abre uma janela popup
// Parâmetros								: I = link, W = width, H = height, S = scrollbar (0/yes)
function PopUp(I, W, H, S){
  lpos = (screen.availWidth/2) - (W/2);
  tpos = (screen.availHeight/2) - (H/2);
  window.open(I,'','status=1,scrollbars='+S+',left='+lpos+',top='+tpos+',width='+W+',height='+H).focus();
}

// inArray									: busca por um elemento em uma array
// Parâmetros								: array = array a ser percorrida, busca = elemento
function inArray(array, busca) {
  for (elemento in array) {
		if (array[elemento]==busca) {
			return true;
		}
	}
	return false;
}

function selectOption(selectID, Option){
	obj = document.getElementById(selectID);
	for(var i=0;i<obj.options.length;i++){
	  if (obj.options[i].value == Option) {
  		obj.options[i].selected = true;
		} else {
  		obj.options[i].selected = false;		
		}
	}
}

<!--
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];}
}
//-->

function mostraCamada(camada) {
	var obj = document.getElementById(camada);
	var posIni=0;
	if (document.body.scrollWidth>770) posIni = (document.body.scrollWidth - 770)/2;	
	obj.style.left = posIni + 17;
	obj.style.display='';
}

function escondeCamada(camada) {
	var obj = document.getElementById(camada);
	obj.style.display='none';
}


// Expandir div

var altura = 0;
var velocidade = 20;
var obj2 = 0;

function extender(obj) {
	var objeto = document.getElementById("texto"+obj);
	var objeto2 = document.getElementById("textoC"+obj);
	objeto.style.display = '';
	altura += velocidade;
	if (!(altura >= objeto.style.zIndex)) {
		objeto.style.height = altura;
		window.setTimeout ("extender("+obj+");", 20);
	} else {
		objeto2.style.display = '';
		document.getElementById("link"+obj).href = "javascript:extender_contrair('"+ obj +"');";
	}
 }
function contrair(obj) {
	var objeto = document.getElementById("texto"+obj);
	var objeto2 = document.getElementById("textoC"+obj);
	objeto2.style.display = 'none';
	altura -= velocidade;
	if (altura != 0) {
		objeto.style.height = altura;
		window.setTimeout ("contrair("+obj+");", 20);
	} else {
		objeto.style.display = 'none';
		objeto.style.height = '0px';
	}
}
function extender_contrair(obj) {
//	altura = parseInt(document.getElementById("texto"+obj).style.height);
//	if (altura <= 0) {
	if (document.getElementById("texto"+obj).style.display == 'none') {
//		extender(obj);
//		document.getElementById("link"+obj).href = 'javascript:;';
		document.getElementById("texto1img"+obj).src = 'imagens/btnDivFechar.gif';
		document.getElementById("texto"+obj).style.display = '';
		document.getElementById("textoC"+obj).style.display = '';
	} else {
//		contrair(obj);
//		document.getElementById("link"+obj).href = 'javascript:;';
		document.getElementById("texto1img"+obj).src = 'imagens/btnDivAbrir.gif';
		document.getElementById("texto"+obj).style.display = 'none';
		document.getElementById("textoC"+obj).style.display = 'none';
	}
}

// Expandir div

/******************************************************************
	showDiv(idDiv, hide)
	hide == 0 --> Mostra a Div
	hide == 1 --> Mostra a Div e esconde a última aberta
	hide == 2 --> Mostra a Div e esconde todas as outras abertas
	hide == 3 --> Esconde todas as Div's
******************************************************************/

var stack = [];
function showDiv(id, hide) {

	var hideDiv;
	var myDiv;

	if ((stack.length != 0) && (hide == 1)) {
		hideDiv = stack.pop();
		myDiv = document.getElementById(hideDiv);
		myDiv.style.display = "none";
	}

	if ((stack.length != 0) && ((hide == 2) || (hide == 3))) {
		for (var i = 0; i <= stack.length; i++) {
			hideDiv = stack.pop();
			myDiv = document.getElementById(hideDiv);
			myDiv.style.display = "none";
		}
	}

	if (hide <= 2) {
		myDiv = document.getElementById(id);
	
		if (myDiv.style.display == "none") {
			myDiv.style.display = "";
			stack.push(id);
		}
	}
}