//configs:
isIE=document.all;
isNN=!document.all&&document.getElementById;
isN4=document.layers;

// Variveis diversas:
var _DiasDaSemna = Array('Domingo','Segunda-feira','Terça-feira','Quarta-feira','Quinta-feira','Sexta-feira','Sábado');
var _Meses = Array('','Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro');


function cep(s){
	s = limpa_string(s);
	if (s.length != 8) {
		return false; 
	}else{
		return true;
	};		
};


function validaCPF(s)	{
	var i;
	s = limpa_string(s);
	var c = s.substr(0,9);
	var dv = s.substr(9,2);
	var d1 = 0;
	for (i = 0; i < 9; i++){
		d1 += c.charAt(i)*(10-i);
	}	
    if (d1 == 0) return false;
	d1 = 11 - (d1 % 11);
	if (d1 > 9) d1 = 0;	
	if ( String(dv.charAt(0)) != String(d1) ){
		return false;
	}
	d1 *= 2;
	for (i = 0; i < 9; i++){
		d1 += c.charAt(i)*(11-i);
	}
	d1 = 11 - (d1 % 11);
	if (d1 > 9) d1 = 0;

	if ( String(dv.charAt(1)) != String(d1)) {
		return false;
	}
    return true;
}

function limpa_string(S){
	var Digitos = "0123456789";
	var temp = "";
	var digito = "";

	for (var i=0; i<S.length; i++)	{
		digito = S.charAt(i);
		if (Digitos.indexOf(digito)>=0)	{
			temp=temp+digito	}
	} //for
	return temp
}



// Aqui inicia as funções de teste do CNPJ
function isNUMB(c){
	if((cx=c.indexOf(","))!=-1)	{		
		c = c.substring(0,cx)+"."+c.substring(cx+1);
	}
	if((parseFloat(c) / c != 1)){
		if(parseFloat(c) * c == 0){
			return(1);
		}else{
			return(0);
		}
	}else{
		return(1);
	}
}

function LIMP(c){
	while((cx=c.indexOf("-"))!=-1){		
		c = c.substring(0,cx)+c.substring(cx+1);
	}
	while((cx=c.indexOf("/"))!=-1){		
		c = c.substring(0,cx)+c.substring(cx+1);
	}
	while((cx=c.indexOf(","))!=-1){		
		c = c.substring(0,cx)+c.substring(cx+1);
	}
	while((cx=c.indexOf("."))!=-1){		
		c = c.substring(0,cx)+c.substring(cx+1);
	}
	while((cx=c.indexOf("("))!=-1){		
		c = c.substring(0,cx)+c.substring(cx+1);
	}
	while((cx=c.indexOf(")"))!=-1){		
		c = c.substring(0,cx)+c.substring(cx+1);
	}
	while((cx=c.indexOf(" "))!=-1){		
		c = c.substring(0,cx)+c.substring(cx+1);
	}
	return(c);
}

function validaCNPJ(CNPJ){
	CNPJ = LIMP(CNPJ);
	if(isNUMB(CNPJ) != 1){
		return(0);
	}else{
		if(CNPJ == 0){
			return(0);
		}else{
			g=CNPJ.length-2;
			if(RealTestaCNPJ(CNPJ,g) == 1){
				g=CNPJ.length-1;
				if(RealTestaCNPJ(CNPJ,g) == 1){	
					return(1);
				}else{
					return(0);
				}
			}else{
				return(0);
			}
		}
	}
}
function RealTestaCNPJ(CNPJ,g){
	var VerCNPJ=0;
	var ind=2;
	var tam;
	for(f=g;f>0;f--){
		VerCNPJ+=parseInt(CNPJ.charAt(f-1))*ind;
		if(ind>8){
			ind=2;
		}else{
			ind++;
		}
	}
	VerCNPJ%=11;
	if(VerCNPJ==0 || VerCNPJ==1){
			VerCNPJ=0;
	}else{
		VerCNPJ=11-VerCNPJ;
	}
	if(VerCNPJ!=parseInt(CNPJ.charAt(g))){
		return(0);
	}else{
		return(1);
	}
}

function abrirJanela(URL,Nome,configs) {
  window.open(URL,Nome,configs);
};

function mascara(campo, Mascara, evtKeyPress) {
      var i, nCount, Texto, tCampo, tMascara,bolMask, retTexto, codTecla;
      if(isIE) { // Internet Explorer
        codTecla = evtKeyPress.keyCode; }
      else if(isNN) { // Nestcape
        codTecla = evtKeyPress.which;
      };
  if (codTecla != 8) { // backspace
      Texto = campo.value;
      // Limpa todos os caracteres de formatação que
      // já estiverem no campo.
	  re = /[^A-Z0-9]/gi
	  Texto = Texto.toString().replace( re, "");
      tCampo = Texto.length;
      tMascara = Mascara.length;
      i = 0;
      nCount = 0;
      retTexto = "";
      tMascara = tCampo;

      while (i <= tMascara) {
		bolMask = ((Mascara.charAt(i) == ":") || (Mascara.charAt(i) == "-") || (Mascara.charAt(i) == ".") || (Mascara.charAt(i) == "/"))
        bolMask = bolMask || ((Mascara.charAt(i) == "(") || (Mascara.charAt(i) == ")") || (Mascara.charAt(i) == " "))
        if (bolMask) {
          retTexto += Mascara.charAt(i);
          tMascara++; 
		} else {
          retTexto += Texto.charAt(nCount);
          nCount++;
        }
        i++;
      }

      campo.value = retTexto;
		if (Mascara.charAt(i-1) == "9") { // so numero
			return ((codTecla > 47) && (codTecla < 58)); // números de 0 a 9
		} else { // livre
			return true;
		};

  } else {
	return true;
  };	
};



function mascaraMoeda(campo, evtKeyPress) {
	  //onKeyPress="return(mascaraMoeda(this,event))"
      var codTecla;
      if(isIE) { // Internet Explorer
        codTecla = evtKeyPress.keyCode; }
      else if(isNN) { // Nestcape
        codTecla = evtKeyPress.which;
      };
/*  if(campo.value=='0,00'){
  	campo.value='';
	if((codTecla > 47) && (codTecla < 58)){
		return true;
	}else{
		return false;
	};
  };
  */
  if (codTecla != 8 && codTecla!=0) { // backspace
	if(((codTecla > 47) && (codTecla < 58)) || String.fromCharCode(codTecla)==',' || String.fromCharCode(codTecla)=='.'){
		if((String.fromCharCode(codTecla)==',' || String.fromCharCode(codTecla)=='.') && campo.value.indexOf(',')!=-1){
			return false;
		}else{
			if(campo.value.length==0 && (String.fromCharCode(codTecla)==',' || String.fromCharCode(codTecla)=='.')){
				return false;
			}else{
				if(campo.value.indexOf(',')!=-1){
						if(String.fromCharCode(codTecla)=='.' || String.fromCharCode(codTecla)==','){
							return false;
						}else{
							return true;
						};				
				}else{
					if(String.fromCharCode(codTecla)=='.'){
						campo.value+=',';
						return false;
					}else{
						return true;
					};
				};
			};
		};
	}else{
		return false;
	};
  } else {
	return true;
  };	
};

function formataMoeda(num) {
	num = num.toString().replace(/[^0-9,]/g,'');		
	num = num.toString().replace(',','.');
	if( parseInt(num) > 0 || parseFloat(num) > 0){
		parseFloat(num);
		if(isNaN(num)){
			num = 0;	
		}else{
			var x = new Number(num);
			num=x.toFixed(2);
		};
		numFormatado=num.toString();
		return numFormatado.replace(/[.]/g,',');
	}else{
		return '0,00';
	};
};



function selItemSelectValor(obj,valorSel){
	for(i=0;i<obj.length;i++){
		if((obj.options[i].value==valorSel) || (obj.options[i].value=='' && obj.options[i].text==valorSel)){
			obj.selectedIndex=i;
		};
	};
};


function hideLayer(Layer){
  if (isIE||isNN) eval(Layer+'.style.visibility="hidden"');
  else if (isN4) eval('document.'+Layer+'.visibility="hide"');
}

function showLayer(Layer){
  if (isIE||isNN) eval(Layer+'.style.visibility="visible"');
  else if (isN4) eval('document.'+Layer+'.visibility="show"');
}
function textoLayer(Layer,texto){
  eval(Layer+'.innerHTML="'+texto+'"');
}

function AdicItemSelect(Sel,Texto,Valor){
	if(Texto==''){
		var NOp = new Option(Texto,Texto);
	}else{
		var NOp = new Option(Texto,Valor);
	};
	Sel.options[Sel.options.length] = NOp; 
};

function MaximizarJanela(){
	window.resizeTo(screen.availWidth,screen.availHeight);
	window.moveTo(screen.availTop,screen.availLeft);
};

//Confere se algum dos Radio do gruopo 'RdBt' foi selecionado
function radioBtconfere(RdBt){
	for(i=0; i<RdBt.length; i++) {
		if(RdBt[i].checked==true){
			return true;
		};
	};
	return false;
};


function marcarChkBox(F,ChkName,ChkV){
/*
Marca/Desmarca todos os checkboxes que o nome contenha a string ChkName
F-> String com o nome do formularios (ex.: document.form1
ChkName->Nome do checkbox (ex.: Filiais  vai marcar todos os chkbox cujo nome contenha Filiais
ChkV -> Valor, 1 marcar, 0 desmarcar
*/
	F=eval(F);
	for (var i = 0; i < F.elements.length; i++) {
		if(F.elements[i].type=='checkbox' && F.elements[i].name.indexOf(ChkName) != -1){
			F.elements[i].checked=ChkV;
		};
	};
};

function conferirChkBox(F,ChkName){
/*
Marca/Desmarcas todos os checkboxes que o nome contenha a string ChkName
F-> String com o nome do formularios (ex.: document.form1
ChkName->Nome do checkbox (ex.: Filiais  vai marcar todos os chkbox cujo nome contenha Filiais 
*/
	F=eval(F);
	for (var i = 0; i < F.elements.length; i++) {
		if(F.elements[i].type=='checkbox' && F.elements[i].name.indexOf(ChkName) != -1){
			if( F.elements[i].checked ){
				return true;
			};
		};
	};
	return false;
};



/////////////////////////////////////////////
//Funcoes de data
/////////////////////////////////////////////
function DateAdd(startDate, numDays, numMonths, numYears){

/*
	var returnDate = new Date(startDate.getTime());
	var yearsToAdd = numYears;	
	var month = returnDate.getMonth()	+ numMonths;
	if (month > 11){
		yearsToAdd = Math.floor((month+1)/12);
		month -= 12*yearsToAdd;
		yearsToAdd += numYears;
	}
	returnDate.setMonth(month);
	returnDate.setFullYear(returnDate.getFullYear()	+ yearsToAdd);
	returnDate.setTime(returnDate.getTime()+60000*60*24*numDays); */
	return returnDate;
};

function DateSub(startDate, numDays, numMonths, numYears){
	var returnDate = new Date(startDate.getTime());
	var yearsToAdd = numYears;	
	var month = returnDate.getMonth()	+ numMonths;
	if (month > 11){
		yearsToAdd = Math.floor((month+1)/12);
		month -= 12*yearsToAdd;
		yearsToAdd += numYears;
	}
	returnDate.setMonth(month);
	returnDate.setFullYear(returnDate.getFullYear()	+ yearsToAdd);
	returnDate.setTime(returnDate.getTime()-60000*60*24*numDays);
	return returnDate;
}

function DateDiff(Dinicio,Dfim){
	if(Dinicio.length!=10 || Dfim.length!=10) return false;
	Di = Dinicio.split('/');
	Df = Dfim.split('/');
	if(Di.length==3 && Df.length==3){
		inicio = new Date(Di[2], Di[1]*1-1, Di[0]);
		fim = new Date(Df[2], Df[1]*1-1, Df[0]);
		dias = Math.floor((fim.getTime() - inicio.getTime()) / (24 * 60 * 60 * 1000));
		return dias;
	};
};

function validaData(data){
	DataRef=data.split('/',3);
	if(DataRef.length!=3){
		return false;
	};
	if( isNaN(DataRef[0]) || !( DataRef[0] >= 1 && DataRef[0] <= 31) ){
		return false;
	};
	if( isNaN(DataRef[1]) || !( DataRef[1] >=1 && DataRef[1] <= 12) ){
		return false;
	};
	if( isNaN(DataRef[2]) || String(DataRef[2]).length!=4 ){
		return false;
	};
	return true;
};

function altTextoSpan(Sp,Txt){
	  document.getElementById(Sp).innerHTML=Txt;
};
