// JavaScript Document
//pega o xmlhttp, faz verificação para browsers diferentes
try{
    xmlhttp = new XMLHttpRequest();
}catch(ee){
    try{
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    }catch(e){
        try{
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }catch(E){
            xmlhttp = false;
        }
    }
}
function setEditar(cod){
	var editar = document.getElementById("edita");
	if(editar.innerHTML != "false"){
		window.location="index.php?menu="+editar.innerHTML+"&acao=edita&cod="+cod;	
	}
	
}
function delFoto(img){
	if(xmlhttp){
		xmlhttp.open("POST", "../conf/ajax.php", true);
		xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=iso-8859-1");
		var dados = "tipo=DelFoto&img="+img;
		xmlhttp.send(dados);
		xmlhttp.onreadystatechange=function() {
			if (xmlhttp.readyState==4){
				var texto=xmlhttp.responseText;
				texto=texto.replace(/\+/g," ");
				texto=unescape(texto);
				if(texto == "ok"){
					window.location.reload();
				}else{
					alert("Não foi possivel excluir a imagem");
				}
			}
		}
	}
}
//seta uma cor quando clicar na consulta
function corClick(o, cor){
	if(o.bgColor == "#90dd6e"){
		o.bgColor="#"+cor;
	}else{
		o.bgColor = "#90dd6e";	
	}
}
//seta focus para o primeiro campo
function setFocus1(){
	var inputs = document.getElementsByTagName("input");
	inputs[0].focus();
}
function setFiltro(id, sql, campos){
	aux_campos = campos.split(",");
	var aux_var = "";
	for(i = 0; i < aux_campos.length; i++){
		var getcampo = document.getElementById(aux_campos[i]);
		if(getcampo.value != ""){
			aux_var += "&filtro["+aux_campos[i]+"]="+getcampo.value;
		}
	}
	if(aux_var != ""){
		if(xmlhttp){
			xmlhttp.open("POST", "../conf/ajax.php", true);
			xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=iso-8859-1");
			var dados = "tipo=SetFiltro&sql="+sql+"&id="+id+aux_var;
			xmlhttp.send(dados);
			xmlhttp.onreadystatechange=function() {
				if (xmlhttp.readyState==4){
					var texto=xmlhttp.responseText;
					//texto=texto.replace(/\+/g," ");
					//texto=unescape(texto);
					sql = texto;
					ajaxDg(id, sql);
				}
			}
		}
	}else{
		var getcampo = document.getElementById(aux_campos[0]);
		getcampo.focus();
	}
}
//pega os dados do DG
function ajaxDg(id, sql, order, tipo, num_pag, qtd_pag){
	//ajaxDg('" . $id . "', '" . urlencode($sql) . "')
	if(xmlhttp){
		xmlhttp.open("POST", "../conf/ajax.php", true);
		xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=iso-8859-1");
		var dados = "tipo=Dg&sql="+sql+"&id="+id+"&order="+order+"&tip="+tipo+"&num_pag="+num_pag+"&qtd_pag="+qtd_pag;
    	xmlhttp.send(dados);
		xmlhttp.onreadystatechange=function() {
			if (xmlhttp.readyState==4){
				var texto=xmlhttp.responseText;
				texto=texto.replace(/\+/g," ");
				texto=unescape(texto);
				var div_dg = document.getElementById("dg_"+id);
				div_dg.innerHTML = texto;
			}
		}
	}
}
//limpa os dados do DG
function clearDg(id){
	var div_dg = document.getElementById("dg_"+id);
	div_dg.innerHTML = "<div align='center'><img src='../icones/carregando.gif'><br />AGUARDE! CONSULTANDO DADOS...</div>";
}
//pega a string do campo2
function ajaxGetString(o, tabela, campo){
	if(xmlhttp){
		xmlhttp.open("POST", "../conf/ajax.php", true);
		xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=iso-8859-1");
		var dados = "tipo=GetString&tabela="+tabela+"&campo="+campo+"&cod="+o.value;
    	xmlhttp.send(dados);
		
		xmlhttp.onreadystatechange=function() {
			if (xmlhttp.readyState==4){
				var texto=xmlhttp.responseText;
				texto=texto.replace(/\+/g," ");
				texto=unescape(texto);
				var destino = document.getElementById(o.name+"string");
				if(texto == "" && o.value != ""){
					o.focus();
					o.value = "";
					destino.value = "";
				}else{
					
					destino.value = texto;
				}
			}
		}
		
	}
}
//pula campo no form
function pula(aux){
	var inputs = document.getElementsByTagName("input");
	for(var i=0;i<inputs.length;i++){
		if(aux == inputs[i].id){
			inputs[i+1].focus();
		}
	}
}
function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}
//apenas numeros
function onlyInt(e){
	var whichCode = (window.Event) ? e.which : e.keyCode;
	if ((whichCode >= 48 && whichCode <= 57) || whichCode == 0 || whichCode == 8){
		return true;	
	}else{
		return false;	
	}
}
//formata para moeda
function formatarMoeda(campo, e){
	var key = ''; 
    var len = 0; 
    var strCheck = '0123456789.'; 
    var aux = ''; 
    var whichCode = (window.Event) ? e.which : e.keyCode; 
    if (whichCode == 13 || whichCode == 8 || whichCode == 0 || whichCode == 45){ 
        return true;  // Enter backspace ou FN qualquer um que não seja alfa numerico 
    } 
    key = String.fromCharCode(whichCode); 
    if (strCheck.indexOf(key) == -1){ 
        return false;  //NÃO E VALIDO 
    }
	
}
//mascara do cpf/cnpj
function CpfCnpjFormat(Campo, e) { 
    var key = ''; 
    var len = 0; 
    var strCheck = '0123456789'; 
    var aux = ''; 
    var whichCode = (window.Event) ? e.which : e.keyCode; 
     
    if (whichCode == 13 || whichCode == 8 || whichCode == 0){ 
        return true;  // Enter backspace ou FN qualquer um que não seja alfa numerico 
    } 
    key = String.fromCharCode(whichCode); 
    if (strCheck.indexOf(key) == -1){ 
        return false;  //NÃO E VALIDO 
    } 
     
    aux =  CpfCnpj_Remove_Format(Campo.value); 
     
    len = aux.length; 
    if(len>=14) { 
        return false;    //impede de digitar um CpfCnpj maior que 14 
    } 
    aux += key; 
     
    Campo.value = CpfCnpj_Mont_Format(aux, Campo); 
    return false; 
} 
//ADDON da mascara do CpfCnpj
function  CpfCnpj_Mont_Format(CpfCnpj, Campo) { 
    var aux = len = ''; 
     
    len = CpfCnpj.length; 
    if(len<=11){ 
        var tipo = 'cpf';
    }else{ 
		var tipo = 'cnpj';
    }
    aux = ''; 
    for(i = 0; i < len; i++) { 
        if(tipo == 'cpf' && (i==3 || i==6)){
			aux	+= '.';
		}
		if(tipo == 'cpf' && i==9){
			aux += '-';	
		}
		if(tipo == 'cnpj' && (i==2 || i==5)){
			aux += '.';				  
		}
		if(tipo == 'cnpj' && i==8){
			aux += '/';
		}
		if(tipo == 'cnpj' && i==12){
			aux += '-';	
		}
        aux += CpfCnpj.charAt(i); 
    }
	if(tipo == 'cpf'){
		valida_cpf(CpfCnpj_Remove_Format(aux), Campo);
	}else{
		valida_cnpj(CpfCnpj_Remove_Format(aux), Campo);	
	}
    return aux;
} 
//ADDON da mascara do CpfCnpj
function  CpfCnpj_Remove_Format(CpfCnpj) { 
    var strCheck = '0123456789'; 
    var len = i = aux = ''; 
    len = CpfCnpj.length; 
    for(i = 0; i < len; i++) { 
        if (strCheck.indexOf(CpfCnpj.charAt(i))!=-1) { 
            aux += CpfCnpj.charAt(i); 
        } 
    } 
    return aux; 
} 
//valida CPF
function valida_cpf(cpf, Campo)
      {
      var numeros, digitos, soma, i, resultado, digitos_iguais;
      digitos_iguais = 1;
      if (cpf.length != 11){
	  		Campo.className = '';
            return false;
	  }
      for (i = 0; i < cpf.length - 1; i++)
            if (cpf.charAt(i) != cpf.charAt(i + 1))
                  {
                  digitos_iguais = 0;
                  break;
                  }
      if (!digitos_iguais)
            {
            numeros = cpf.substring(0,9);
            digitos = cpf.substring(9);
            soma = 0;
            for (i = 10; i > 1; i--)
                  soma += numeros.charAt(10 - i) * i;
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if (resultado != digitos.charAt(0)){
                  Campo.className = 'fundo_vermelho';
				  return false;
				  
			}
            numeros = cpf.substring(0,10);
            soma = 0;
            for (i = 11; i > 1; i--)
                  soma += numeros.charAt(11 - i) * i;
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if (resultado != digitos.charAt(1)){
                  Campo.className = 'fundo_vermelho';
				  return false;
				  
			}
            Campo.className = 'fundo_verde';
			return true;
			
            }
      else
            Campo.className = 'fundo_vermelho';
			return false;
			
      }
//valida CNPJ
function valida_cnpj(cnpj, Campo)
      {
	  var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais;
      digitos_iguais = 1;
      if (cnpj.length < 14){
		    Campo.className = '';
            return false;
	  }
      for (i = 0; i < cnpj.length - 1; i++)
            if (cnpj.charAt(i) != cnpj.charAt(i + 1))
                  {
                  digitos_iguais = 0;
                  break;
                  }
      if (!digitos_iguais)
            {
            tamanho = cnpj.length - 2
            numeros = cnpj.substring(0,tamanho);
            digitos = cnpj.substring(tamanho);
            soma = 0;
            pos = tamanho - 7;
            for (i = tamanho; i >= 1; i--)
                  {
                  soma += numeros.charAt(tamanho - i) * pos--;
                  if (pos < 2)
                        pos = 9;
                  }
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if (resultado != digitos.charAt(0)){
				  Campo.className = 'fundo_vermelho';
                  return false;
			}
            tamanho = tamanho + 1;
            numeros = cnpj.substring(0,tamanho);
            soma = 0;
            pos = tamanho - 7;
            for (i = tamanho; i >= 1; i--)
                  {
                  soma += numeros.charAt(tamanho - i) * pos--;
                  if (pos < 2)
                        pos = 9;
                  }
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if (resultado != digitos.charAt(1)){
                  Campo.className = 'fundo_vermelho';
				  return false;
			}
			Campo.className = 'fundo_verde';
            return true;
            }
      else
            Campo.className = 'fundo_vermelho';
			return false;		
}
//mascara do telefone: (##)####-###
function TelefoneFormat(Campo, e) { 
    var key = ''; 
    var len = 0; 
    var strCheck = '0123456789'; 
    var aux = ''; 
    var whichCode = (window.Event) ? e.which : e.keyCode; 
     
    if (whichCode == 13 || whichCode == 8 || whichCode == 0){ 
        return true;  // Enter backspace ou FN qualquer um que não seja alfa numerico 
    } 
    key = String.fromCharCode(whichCode); 
    if (strCheck.indexOf(key) == -1){ 
        return false;  //NÃO E VALIDO 
    } 
     
    aux =  Telefone_Remove_Format(Campo.value); 
     
    len = aux.length; 
    if(len>=10) { 
        return false;    //impede de digitar um telefone maior que 10 
    } 
    aux += key; 
     
    Campo.value = Telefone_Mont_Format(aux); 
    return false; 
} 
//ADDON da mascara do telefone: (##)####-###
function  Telefone_Mont_Format(Telefone) { 
    var aux = len = ''; 
     
    len = Telefone.length; 
    if(len<=9){ 
        tmp = 5; 
    }else{ 
        tmp = 6; 
    } 
     
    aux = ''; 
    for(i = 0; i < len; i++) { 
        if(i==0){ 
            aux = '('; 
        } 
        aux += Telefone.charAt(i); 
        if(i+1==2){ 
            aux += ')'; 
        } 
         
        if(i+1==tmp){ 
            aux += '-'; 
        } 
    } 
    return aux ; 
} 
//ADDON da mascara do telefone: (##)####-###
function  Telefone_Remove_Format(Telefone) { 
    var strCheck = '0123456789'; 
    var len = i = aux = ''; 
    len = Telefone.length; 
    for(i = 0; i < len; i++) { 
        if (strCheck.indexOf(Telefone.charAt(i))!=-1) { 
            aux += Telefone.charAt(i); 
        } 
    } 
    return aux; 
} 
function popup_mostra(tabela, campo){
	var fundo = document.getElementById("popup_fundo");
	var popup = document.getElementById("popup");
	fundo.style.display = "block";
	popup.style.display = "block";
	popup.innerHTML = "<div align='center'><img src='../icones/carregando.gif'><br />AGUARDE! CONSULTANDO DADOS...</div>";
	if(xmlhttp){
		xmlhttp.open("GET", "../adminis/popup_consulta.php?tabela="+tabela+"&campo="+campo, true);
		xmlhttp.onreadystatechange=function() {
			if (xmlhttp.readyState==4){
				var texto=xmlhttp.responseText;
				texto=texto.replace(/\+/g," ");
				texto=unescape(texto);
				if(texto == "" && o.value != ""){
					var aux = false;
				}else{
					var aux = true;
					popup.innerHTML = "<div id=\"dg_popup\" class=\"dg\"><div align='center'><img src='../icones/carregando.gif'><br />AGUARDE! CONSULTANDO DADOS...</div></div>";
					var script1 = "try{    xmlhttp = new XMLHttpRequest();}catch(ee){    try{        xmlhttp = new ActiveXObject(\"Msxml2.XMLHTTP\");    }catch(e){        try{            xmlhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");        }catch(E){            xmlhttp = false;        }    }}";
					var script2 = "function ajaxDg(id, sql, order, tipo, num_pag, qtd_pag){	if(xmlhttp){	xmlhttp.open(\"POST\", \"../conf/ajax.php\", true);		xmlhttp.setRequestHeader(\"Content-Type\", \"application/x-www-form-urlencoded; charset=iso-8859-1\");		var dados = \"tipo=Dg&sql=\"+sql+\"&id=\"+id+\"&order=\"+order+\"&tip=\"+tipo+\"&num_pag=\"+num_pag+\"&qtd_pag=\"+qtd_pag;    	xmlhttp.send(dados);		xmlhttp.onreadystatechange=function() {			if (xmlhttp.readyState==4){				var texto=xmlhttp.responseText;				texto=texto.replace(/\\+/g,\" \");				texto=unescape(texto);				var div_dg = document.getElementById(\"dg_\"+id);				div_dg.innerHTML = texto;			}		}	}}";
					eval(script1);
					eval(script2);
					eval(texto);
					fundo.style.display = "block";
					popup.style.display = "block";
				}
			}
		}
		xmlhttp.send(null);
	}	
}
function popup_some(){
	var fundo = document.getElementById("popup_fundo");
	var popup = document.getElementById("popup");
	popup.innerHTML = "<div align='center'><img src='../icones/carregando.gif'><br />AGUARDE! CONSULTANDO DADOS...</div>";
	fundo.style.display = "none";
	popup.style.display = "none";
}
//joga as 2 primeiras colunas no popup para os campos
function SetString(campo, valor1, valor2){
	var campo1 = document.getElementById(campo);
	var campo2 = document.getElementById(campo+'string');
	campo1.value = valor1;
	campo2.value = valor2;
	popup_some();
}
//troca cor na consulta
function corOver(o){
	if(o.bgColor != "#90dd6e"){
		o.bgColor="#EFD600";
	}
}
//volta cor na consulta
function corOut(o, cor){
	if(o.bgColor != "#90dd6e"){
		o.bgColor="#"+cor;
	}
}
//valida data
function dataVerifica(objeto){
	problema=false;
	qtBarra=0;
	tamanho=objeto.value.length;
	if(tamanho>4){
		caracteres="0123456789/";
		for(i=0;i<tamanho;i++){
			algarismo=objeto.value.substring(i,i+1);
			if((caracteres.search(algarismo)==-1)&&!(problema)){
				msg="Data inválida!\n";
				msg+=" - Data informada: "+objeto.value+"\n\n";
				msg+="Verificação: \n";
				msg+=" - Caracter informado inválido;\n\n";
				msg+="Informações úteis: \n";
				msg+=" - Caracteres válidos para compor a data: \n   -> 1,2,3,4,5,6,7,8,9,0 e '/'(separador);\n";
				//alert(msg);
				return msg;
				problema=true;
			}
			if(algarismo=="/"){
				qtBarra++;
			}
		}
		if(!(problema)){
			if(qtBarra>2){
				msg="Data inválida!\n";
				msg+=" - Data informada: "+objeto.value+"\n\n";
				msg+="Verificação: \n";
				msg+=" - Caracter informado inválido;\n\n";
				msg+="Informações úteis: \n";
				msg+=" - Caracteres válidos para compor a data: \n   -> 1,2,3,4,5,6,7,8,9,0 e '/'(separador);\n";
				msg+=" - Formato da data: dd/mm/aaaa";
				//alert(msg);
				return msg;
				problema=true;
			}
		}
		if(!(problema)){
			for(i=0;i<tamanho;i++){
				algarismo=objeto.value.substring(i,i+1);
				if(algarismo=="/"){
					if(i==1){
						objeto.value="0"+objeto.value;
					}
					else
					if(i==4){
						objeto.value=objeto.value.substring(0,3)+"0"+objeto.value.substring(3,10);
					}
				}
			}
			tamanho=objeto.value.length;
			if(tamanho<10){
				ano=parseFloat(objeto.value.substring(6,10));
				if((ano>0)&&(ano<30)){
					anoi="20";
					if(ano<10){
						anoi="200";
					}
					objeto.value=objeto.value.substring(0,6)+""+anoi+ano;
				}
				if((ano>29)&&(ano<100)){
					objeto.value=objeto.value.substring(0,6)+"19"+ano;
				}
				if((ano>99)&&(ano<999)){
					objeto.value=objeto.value.substring(0,6)+"0"+ano;
				}
			}
		}
		tamanho=objeto.value.length;
		dia=objeto.value.substring(0,2);
		mes=objeto.value.substring(3,5);
		ano=objeto.value.substring(6,10);
		barra1=objeto.value.substring(2,3);
		barra2=objeto.value.substring(5,6);
		if(!(problema)){
			if((barra1!="/")||(barra2!="/")){
				//alert("Formato da data inválido. Exemplo: 01/01/2002");
				return "Formato da data inválido. Exemplo: 01/01/2002";
				problema=true;
			}
		}
		if(!(problema)){
			if(tamanho!=10){
				msg="Ano informado inválido!\n";
				msg+=" - Ano Informado: "+ano+"\n\n";
				msg+="Verificação: \n";
				msg+=" - Ano informado diferente do formato (aaaa);\n\n";
				msg+="Informações úteis: \n";
				msg+=" - O ano deve conter 4 caracteres;\n";
				//alert(msg);
				return msg;
				problema=true;
			}
		}
		if(!(problema)){
			if((parseFloat(mes)>12)||(parseFloat(mes)<1)){
				msg="Mês informado inválido!\n";
				msg+=" - Mês Informado: "+mes+"\n\n";
				msg+="Verificação: \n";
				msg+=" - Dia informado maior que 12;\n";
				msg+=" - Mês Informado menor que 01;\n\n";
				msg+="Informações úteis: \n";
				msg+=" - Mês informado: "+mes+";\n";
				//alert(msg);
				return msg;
				problema=true;
			}
		}
		if(!(problema)){
			maiorDia=new Date(ano,mes,0);
			maiorDia=maiorDia.getDate();
			if((parseFloat(dia)>maiorDia)||(parseFloat(dia)<1)){
				msg="Dia informado inválido!\n";
				msg+=" - Dia Informado: "+dia+"\n\n";
				msg+="Verificação: \n";
				msg+=" - Dia informado igual a 00;\n";
				msg+=" - Dia informado não existe no mês informado;\n\n";
				msg+="Informações úteis: \n";
				msg+=" - Mês informado: "+mes+";\n";
				msg+=" - Último dia do mês: "+maiorDia+";";
				//alert(msg);
				return msg;
				problema=true;
			}
		}
	}
	else
	if(tamanho>0){
		msg="Data inválida!\n";
		msg+=" - Data informada: "+objeto.value+"\n\n";
		msg+="Verificação: \n";
		msg+=" - Data incompleta;\n\n";
		msg+="Informações úteis: \n";
		msg+=" - Formato da data: dd/mm/aaaa";
		//alert(msg);
		return msg;
		problema=true;
	}
	if(problema){
		objeto.value="";
		objeto.focus();
		return true;
	}else{
		return "";	
	}
}
function dataCompleta(objeto){
	var whichCode = (window.Event) ? objeto.which : objeto.keyCode;
	
	if(whichCode != 8){
		tamanho=objeto.value.length;
		if(((tamanho==2)&&(objeto.value.substring(1,2)!="/"))||((tamanho==5)&&!((objeto.value.substring(3,4)=="/")||
			(objeto.value.substring(4,5)=="/"))&&(objeto.value.substring(1,2)!="/"))){
			objeto.value=objeto.value+"/";}
	}
}