//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(objTextBox, SeparadorMilesimo, SeparadorDecimal, e){
	if(objTextBox.value.length >= 15)
	{
		return false;
	}
	else
	{   var sep = 0;
	    var key = '';
	    var i = j = 0;
	    var len = len2 = 0;
	    var strCheck = '0123456789';
	    var aux = aux2 = '';
	    var whichCode = (window.Event) ? e.which : e.keyCode;

		//---------------------------------

            if ( whichCode == 8) {

                sValue = document.getElementById('moeda').value;

                sValue = sValue.toString().replace( ".", "" );
                sValue = sValue.toString().replace( " ", "" );
                sValue = sValue.toString().replace( ",", "" );
                fldLen = sValue.length;

                i = 0;
                nCount = 0;
                sCod = "";
                mskLen = fldLen;
                sMask = SeparadorMilesimo+" "+SeparadorDecimal;

                    if (whichCode != 8) { // backspace
                    if (sMask.charAt(i-1) == "9") { // apenas números...
                    return ((whichCode > 47) && (whichCode < 58)); }
                    else { // qualquer caracter...
                    return true;
                    }
                    }
                    else {
                    return true;
                    }

           }
                //------------------------------------
            if (whichCode == 13) return true;
            key = String.fromCharCode(whichCode); // Valor para o código da Chave
            if (strCheck.indexOf(key) == -1) return false; // Chave inválida
            len = objTextBox.value.length;

            for(i = 0; i < len; i++)
                if ((objTextBox.value.charAt(i) != '0') && (objTextBox.value.charAt(i) != SeparadorDecimal)) break;
            aux = '';
            for(; i < len; i++)
                if (strCheck.indexOf(objTextBox.value.charAt(i))!=-1) aux += objTextBox.value.charAt(i);
            aux += key;
            len = aux.length;
            if (len == 0) objTextBox.value = '';
            if (len == 1) objTextBox.value = '0'+ SeparadorDecimal + '0' + aux;
            if (len == 2) objTextBox.value = '0'+ SeparadorDecimal + aux;
            if (len > 2) {
                aux2 = '';
                for (j = 0, i = len - 3; i >= 0; i--) {
                    if (j == 3) {
                        aux2 += SeparadorMilesimo;
                        j = 0;
                    }
                    aux2 += aux.charAt(i);
                    j++;
                }
                objTextBox.value = '';
                len2 = aux2.length;
                for (i = len2 - 1; i >= 0; i--)
                objTextBox.value += aux2.charAt(i);
                objTextBox.value += SeparadorDecimal + aux.substr(len - 2, len);
            }
            return false;
        }

}
function formataMoeda(num) {
	num = num.toString().replace(/[^0-9,\-]/g,'');		
	num = num.toString().replace(',','.');
	if ((parseInt(num) > 0 || parseFloat(num) > 0) || (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 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 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 sairSistema(){
    if(confirm('Deseja realmente abandonar o sistema?')){
            document.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=no,width=800,height=600');
};


//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;
};
/**
 * Função que esconde ou expande um elemento
 * @param string idDados - id do elemento
 * @param string idImg - id da imagem que será usada quando se clicar
 */
function extras(idDados,idImg){//usado para suprimir e expandir os campos no form

    if(document.getElementById(idDados).style.display == 'none') {
            $('#'+idDados).show('slow');
             document.getElementById(idImg).setAttribute('src', 'imgs/menos.gif');
             document.getElementById(idImg).setAttribute('title', 'Suprimir');
    }else {
        $('#'+idDados).hide('slow');
        document.getElementById(idImg).setAttribute('src', 'imgs/mais.gif');
        document.getElementById(idImg).setAttribute('title', 'Expandir');
    }
};

function MsgErroCampos(msg,Campo,ClassCampo,ClassMsg,Cor){

    msgErro = "<div style='color:red; font-size:13;' > "+msg+"<img src='imagens/no.png'></div>";
    $(Campo+"."+ClassCampo).css({backgroundColor:"#FF0000"});
    $("div."+ClassMsg).html(msgErro);
};
function MsgOk(ClassCampo,Campo,ClassMsg,Cor){
    ok = "<div style='color:#FFFFFF; font-size:13;' ><img src='imagens/yes.png'></div>";
    $(Campo+"."+ClassCampo).css({backgroundColor:"#FFFFFF"});
    $("div."+ClassMsg).html(ok);
};
function MsgLimpa(ClassCampo,Campo,ClassMsg,Cor){
    limpa = "<div style='color:#FFFFFF; font-size:13;' ></div>";
    $(Campo+"."+ClassCampo).css({backgroundColor:"#FFFFFF"});
    $("div."+ClassMsg).html(limpa);
};
/**
 * Funçao faz imagem opaco
 * @param id - id do elemento
 */
function opaco(id){
     $(id).css({"z-index":"1000","opacity":"0.4", "filter":"alpha(opacity=50)"});
}
/**
 * Funçao faz imagem normal
 * @param id - id do elemento
 */
function normal(id){
     $(id).css({"z-index":"1000","opacity":"20", "filter":"alpha(opacity=100)"});
}
/**
 * Função que gera uma janela com mensagem de erro ou acerto
 * @param string titulo - titulo da tela de mensagem
 * @param strinng msg - mensagem(erro) ou comfirmação
 * @param string status - indica se a mensagem e de erro ou não (para indicar a cor )
 */
function Msg(titulo,msg,status){

    if(status =='erro'){
        $('#dialog').html('<span class="MsgErro">'+msg+'</span><br>');
     }else{
        $('#dialog').html('<span class="MsgOk">'+msg+'</span><br>');
     }
        $('#dialog').dialog({
            width: 400,
            modal: true,
            buttons: {
                "Ok": function() {
                    $(this).dialog("close");
                }
            },
            title:titulo
        });
        $('#dialog').dialog('open');
}
/**
 * Função que gera uma janela com mensagem que pede confirmação de tarefa(em desenvolvimento)
 * @param string titulo - titulo da tela de mensagem
 * @param strinng msg - mensagem
 */
function MsgConfirma(titulo,msg){
        $('#dialog').html('<br><span class="MsgOk">'+msg+'</span><br><br><br>');
        $('#dialog').dialog({
            width: 300,
            modal: true,
            buttons: {
                "Ok": function() {
                    
                    $(this).dialog("close");
                    return true;
                },
                "Cancela": function(){                   
                    $(this).dialog("close");
                    return false;
                }
            },
            title:titulo          
        });
        $('#dialog').dialog('open');     
}

