//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
}



function validaEmail(emailStr) {
	var checkTLD=1;
	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
	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("Email address seems incorrect (check @ and .'s)");
		return false;
	}
	var user=matchArray[1];
	var domain=matchArray[2];
	for (i=0; i<user.length; i++) {
	if (user.charCodeAt(i)>127) {
		//alert("Ths username contains invalid characters.");
		return false;
	   }
	}
	for (i=0; i<domain.length; i++) {
	if (domain.charCodeAt(i)>127) {
		//alert("Ths domain name contains invalid characters.");
		return false;
	   }
	}
	if (user.match(userPat)==null) {
		//alert("The username doesn't seem to be valid.");
		return false;
	}
	var IPArray=domain.match(ipDomainPat);
	if (IPArray!=null) {
	for (var i=1;i<=4;i++) {
	if (IPArray[i]>255) {
	//	alert("Destination IP address is invalid!");
		return false;
	   }
	}
	return true;
	}
	var atomPat=new RegExp("^" + atom + "$");
	var domArr=domain.split(".");
	var len=domArr.length;
	for (i=0;i<len;i++) {
	if (domArr[i].search(atomPat)==-1) {
		//alert("The domain name does not seem to be valid.");
		return false;
	   }
	}
	
	if (checkTLD && domArr[domArr.length-1].length!=2 && 
		domArr[domArr.length-1].search(knownDomsPat)==-1) {
			//alert("The address must end in a well-known domain or two letter " + "country.");
			return false;
		}
		if (len<2) {
			//alert("This address is missing a hostname!");
			return false;
		}
		return true;
};

// 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 sairSistema(){
	if(confirm('Deseja realmente abandonar o sistema?')){
		location='sair.php';
	};
};

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


function Relatorios(Rel) {
	Url='relatorios.php?mod='+Rel;
	abrirJanela(Url,'rel','menubar=yes,scrollbars=yes,resizable=yes,width=800,height=600');
};


//Confere se algum dos Radio do gruopo 'RdBt' foi selecionado
function radioBtconfere(RdBt){
	if(typeof(RdBt.length)=='undefined'){
		if(RdBt.checked==true){
			return true;
		};
		return false;				
	}else{
		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){
	tmp = data.split('/', 3);
	if (tmp.length != 3) {
		return false;
	};	
	dia = parseInt(tmp[0], 10);
	mes = parseInt(tmp[1], 10);
	ano = parseInt(tmp[2], 10);
	anoAtual = new Date().getFullYear();	
	if (isNaN(dia) || !(dia >= 1 && dia <= 31)) {
		return false;
	};
	if (isNaN(mes) || !(mes >=1 && mes <= 12)) {
		return false;
	};
	if (isNaN(ano) || ano < 1900 || ano > (anoAtual + 20)) {
		return false;
	};
    if (mes == 2 && (((ano % 4) != 0 && dia > 28) || ((ano % 4) == 0 && dia > 29))) { //fevereiro
		return false;
	}	
    if ((mes == 4 || mes == 6 || mes == 9 || mes == 11 ) && dia > 30) {
		return false;		
	};
	return true;
};

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

function displayTR(id, mostrar){
	if(document.getElementById && document.createTextNode){
		var tr=document.getElementById(id);
		if(tr){
			if(mostrar){
				try {
					tr.style.display='table-row';
				} catch(e) {
					tr.style.display = 'block';
				};				
			}else{
				tr.style.display='none';				
			};
		};
	};	  
}


/**
 * Converte um valor em formado de moeda pra flot do javascript
 */
function moedaToFloat(valor) {
    if (typeof(valor) != 'string') return NaN;
    if (valor.length == 0) return NaN;
    valor = valor.replace('.','');
    valor = valor.replace(',','.');
    return parseFloat(valor);
};



function number_format( number, decimals, dec_point, thousands_sep ) {
    // Formats a number with grouped thousands
    //
    // version: 906.1806
    // discuss at: http://phpjs.org/functions/number_format
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://getsprink.com)
    // +     bugfix by: Benjamin Lupton
    // +     bugfix by: Allan Jensen (http://www.winternet.no)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +     bugfix by: Howard Yeend
    // +    revised by: Luke Smith (http://lucassmith.name)
    // +     bugfix by: Diogo Resende
    // +     bugfix by: Rival
    // +     input by: Kheang Hok Chin (http://www.distantia.ca/)
    // +     improved by: davook
    // +     improved by: Brett Zamir (http://brett-zamir.me)
    // +     input by: Jay Klehr
    // +     improved by: Brett Zamir (http://brett-zamir.me)
    // +     input by: Amir Habibi (http://www.residence-mixte.com/)
    // +     bugfix by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: number_format(1234.56);
    // *     returns 1: '1,235'
    // *     example 2: number_format(1234.56, 2, ',', ' ');
    // *     returns 2: '1 234,56'
    // *     example 3: number_format(1234.5678, 2, '.', '');
    // *     returns 3: '1234.57'
    // *     example 4: number_format(67, 2, ',', '.');
    // *     returns 4: '67,00'
    // *     example 5: number_format(1000);
    // *     returns 5: '1,000'
    // *     example 6: number_format(67.311, 2);
    // *     returns 6: '67.31'
    // *     example 7: number_format(1000.55, 1);
    // *     returns 7: '1,000.6'
    // *     example 8: number_format(67000, 5, ',', '.');
    // *     returns 8: '67.000,00000'
    // *     example 9: number_format(0.9, 0);
    // *     returns 9: '1'
    // *     example 10: number_format('1.20', 2);
    // *     returns 10: '1.20'
    // *     example 11: number_format('1.20', 4);
    // *     returns 11: '1.2000'
    // *     example 12: number_format('1.2000', 3);
    // *     returns 12: '1.200'
    var n = number, prec = decimals;

    var toFixedFix = function (n,prec) {
        var k = Math.pow(10,prec);
        return (Math.round(n*k)/k).toString();
    };

    n = !isFinite(+n) ? 0 : +n;
    prec = !isFinite(+prec) ? 0 : Math.abs(prec);
    var sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep;
    var dec = (typeof dec_point === 'undefined') ? '.' : dec_point;

    var s = (prec > 0) ? toFixedFix(n, prec) : toFixedFix(Math.round(n), prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;

    var abs = toFixedFix(Math.abs(n), prec);
    var _, i;

    if (abs >= 1000) {
        _ = abs.split(/\D/);
        i = _[0].length % 3 || 3;

        _[0] = s.slice(0,i + (n < 0)) +
              _[0].slice(i).replace(/(\d{3})/g, sep+'$1');
        s = _.join(dec);
    } else {
        s = s.replace('.', dec);
    }

    var decPos = s.indexOf(dec);
    if (prec >= 1 && decPos !== -1 && (s.length-decPos-1) < prec) {
        s += new Array(prec-(s.length-decPos-1)).join(0)+'0';
    }
    else if (prec >= 1 && decPos === -1) {
        s += dec+new Array(prec).join(0)+'0';
    }
    return s;
}
