/* ----------------------------------------------------------------------------------------------- */
/**
 *
 * Banco de Funções javascript
 * Julho de 2006
 * @author Daniane P. Gomes <danianepg@gmail.com>
 * @version 0.1
 *
 */
/* ----------------------------------------------------------------------------------------------- */

	/**
	 * Carrega foco no formulário
	 * @param Campo que receberá o foco
	 */
	 
	function foco(NmCampo){
		document.getElementById(NmCampo).focus();		
	}
	
	/* ------------------------------------------------------------------------------------------- */
	
	function imprimir(){
		window.print();
	}

	/* ------------------------------------------------------------------------------------------- */
	
	/**
	 * Seleciona todos os checkbox
	 */

	function selTodos (pai, tform){
		for (var i = 1 ; i < tform.elements.length; i++) {
			if (tform.elements[i].type == "checkbox") {
				if (tform.elements[i].disabled == false) {
					if (tform.elements[i].checked == false) { 
						tform.elements[i].checked = true;
					} else {
						tform.elements[i].checked = false;
					}
				}
			}
		}
	}
	
	/**
	 * Seleciona todos os checkbox
	 * @version 2.0
	 * @param Valor do check que faz marcar ou desmarcar todos
	 * @param Id dos campos que deverão ser marcados
	 * @param Quantidade de campos
	 */
	
	function selTodos2(fgMarcado,nmId,nrQtd){
		
		if		(document.getElementById(fgMarcado).checked == true)   fgMarcaDes = true;
		else if (document.getElementById(fgMarcado).checked == false)  fgMarcaDes = false;

		for(d=1;d<=nrQtd;d++){			
			
			fgMarca = nmId+d;
			document.getElementById(fgMarca).checked = fgMarcaDes;
		}
	}
	
	
	/* ------------------------------------------------------------------------------------------- */

	/**
	 * Verifica objetos para exclusão
	 */

	function verificaChecked(tform){
		result=0;
		for(var i=1;i<tform.elements.length;i++) {
			if (tform.elements[i].type=="checkbox" && tform.elements[i].checked && tform.elements[i].name!="chkexclusao") {
				result++;
			}
		}
	
		if(result==0){ 
			alert("Nenhum objeto selecionado para exclusão!"); return false;
		} else {
			result=confirm("Confirma a exclusão de "+result+" registro(s)?");
		}
		return result;
	}
 
	/* ------------------------------------------------------------------------------------------- */

	/**
	 * Obriga o preenchimento de campos
	 * @param Id do campo que deve ser validado
	 */
	
	function validaCampo(idCampo,nmMsg){
		
		var nmCampo 	= document.getElementById(idCampo);
		
		if(nmMsg!='')
			var nmAlertMsg 	= "Preencha o campo referente "+nmMsg;
				
		if(nmCampo.value=='' || nmCampo.value<=0) {
			if(nmAlertMsg !='') {
				alert(nmAlertMsg);
			}
			
			nmCampo.focus();
			document.getElementById('fgSub').value = 0;
			return false;
		} else {
			return true;	
		}
	} 	

	/* ------------------------------------------------------------------------------------------- */
	
	/**
	 * Compara se um campo digitado é igual a outro
	 * @param String com os dados. Para mais que um separar por ;
	 * @param String informada pelo usuário
	 * @param Mensagem de erro
	 * @return boolean
	 */
	function comparaString(nmString,nmCompara,nmMsg){
		
		nmString 	= document.getElementById(nmString);
		nmCompara	= document.getElementById(nmCompara);
		
		if(nmMsg=='')
			nmMsg = "Já existe registro idêntico a esse!";
		
		nmString = nmString.value.split(";");
		
		for(d=0;d<nmString.length;d++){
			if(nmString[d]==nmCompara.value){
				alert(nmMsg);
				document.getElementById('fgSub').value = 0;
				nmCompara.focus();
				return false;
			}		
		}
				
	}

	/* ------------------------------------------------------------------------------------------- */

	/**
	 * Valida endereço de e-mail
	 * @param Id da string a ser validada
	 * @param Mensagem de alerta
	 */
	
	function validaEmail(nmString,nmMsg){
		
		nmString = document.getElementById(nmString);
		
		if(nmMsg==''){
			nmMsg = "Um ou mais endereços de e-mail inválido(s)!";
		}
		
		nmInvalid = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/;
		nrPtVirg  = nmString.value.indexOf(";");
		if(nrPtVirg>0){
			
			vetStr = nmString.value.split(";");
			nrTam  = vetStr.length;
			
			for(d=0;d<nrTam;d++){
				if(nmInvalid.test(vetStr[d])==false){
					alert(nmMsg);
					nmString.style.color = "red";
					nmString.focus();
					document.getElementById('fgSub').value = 0;
					return false;
				}
			}
		
		} else {
			if(nmInvalid.test(nmString.value)==false){
				alert(nmMsg);
				nmString.style.color = "red";
				nmString.focus();
				document.getElementById('fgSub').value = 0;
				return false;
			} else {
				return true;
			}
		}
		
	}


	/* ------------------------------------------------------------------------------------------- */

	/**
	 * Bloqueia os caracteres definidos no segundo parâmetro
	 * @param String que está sendo analisada
	 * @param String separada por espaços, contendo os caracteres que devem ser bloqueados
	 * @return boolean
	 */
	 
	 function bloq(nmCampo,nmStringVet){
	 	
		nmCampo  = document.getElementById(nmCampo);
		vetStr	 = nmStrBloq.split(" ");
		
		for(d=0;d<vetStr.length;d++){
			if(vetStr[d]!='' && vetStr[d]!='undefined'){
				nmProcura = nmCampo.value.indexOf(vetStr[d]);
				if(nmProcura!=-1){
					nmPos 		  = nmCampo.value.substr(0,nmProcura);
					nmCampo.value = nmPos;
					return false;
				}
			}
		}
	 }
	 
	 
	 /**
	  * Monsta um string exceção para bloqueios, removendo os campos informados
	  * @param String oficial
	  * @param Exceções a serem desbloqueadas
	  * @return String reorganizada
	  */ 
	 function desbloq(nmString,nmDel){

		vetStr 	 = nmString.split(" ");
		vetDel 	 = nmDel.split(" ");
		nmStrOrg = "";
		
		for(d=0;d<vetDel.length;d++){
			for(e=0;e<vetStr.length;e++){
				if(vetDel[d]==vetStr[e]){
					vetStr[e] = null;
				} 				
			}
		}
		
		return limpaStr(vetStr);
	 }
	 

	 /**
	  * Retira as posições nulas de um vetor
	  * @param Vetor a ser limpado	  
	  * @return String reorganizada
	  */ 
	  
	 function limpaStr(vetStr){

		nmRetorno = "";
		for(d=0;d<vetStr.length;d++){
			if(vetStr[d]!=null){
				nmRetorno += vetStr[d]+" ";
			}
		}
		
		return nmRetorno;
	 }
	 

     /**
	  * Bloqueia letras com o auxílio da função bloq
	  * String que está sendo analisada
	  * String adicional para ser bloqueada
	  * String de exceção que não deve ser bloqueada
	  */
	  
	 function bloqLetras(nmCampo,nmAdd,nmDel){
	 
		nmStrBloq  = "a b c ç d e f g h i j k l m n o p q r s t u v w x y z ";
		nmStrBloq += "A B C Ç D E F G H I J K L M N O P Q R S T U V W X Y Z ";
		nmStrBloq += "á à ã â é è ê í ì î ó ò õ ô ú ù û ";
		nmStrBloq += "Á À Â Ã É È Ê Í Ì Î Ó Ò Õ Ô Ú Ù Û";
		
		if(nmAdd!='')
			nmStrBloq += nmAdd;

		if(nmDel!='')
			nmStrBloq = desbloq(nmStrBloq,nmDel);
		
		return bloq(nmCampo,nmStrBloq);	 	
	 }   

	 
     /**
	  * Bloqueia caracteres com o auxílio da função bloq
	  * String que está sendo analisada
	  * String adicional para ser bloqueada
	  * String de exceção que não deve ser bloqueada
	  */
	
	function bloqCaracter(nmCampo,nmAdd,nmDel){
		
		nmStrBloq  = "\" ! @ # $ % ¨ & * ( ) _ + ' - = ³ ¬ ¢ § ´ [ ~ ] , . ; / ` { ^ } < > : ? ° º \ |";
		
		if(nmAdd!='')
			nmStrBloq += nmAdd;
			
		if(nmDel!='')
			nmStrBloq = desbloq(nmStrBloq,nmDel);
	
		return bloq(nmCampo,nmStrBloq);	 
	}


     /**
	  * Bloqueia números com o auxílio da função bloq
	  * String que está sendo analisada
	  * String adicional para ser bloqueada
	  * String de exceção que não deve ser bloqueada
	  */
	
	function bloqNum(nmCampo,nmAdd,nmDel){
		
		nmStrBloq  = "0 1 2 3 4 5 6 7 8 9";
		
		if(nmAdd!='')
			nmStrBloq += nmAdd;

		if(nmDel!='')
			nmStrBloq = desbloq(nmStrBloq,nmDel);

		return bloq(nmCampo,nmStrBloq);	 
	}



	/* ------------------------------------------------------------------------------------------- */

	/**
	 * Tenta validar um domínio buscando pelo menos um ponto e não permitindo que a posição [1] tenha 
	 * mais de 3 caracteres e a posição [2] mais de 2 caracteres
	 * @param String que será analisada
	 */
	
	function validaDominio(nmStr) {
		
		nmString 	= document.getElementById(nmStr);
		nmMsg 		= "Domínio inválido!";
		nrPt  		= nmString.value.indexOf(".");	
		
		if(nrPt==-1){
			alert(nmMsg);
			nmString.style.color = "red";
			nmString.focus();
			return false;
			
		} else {
			
			if(validaSite(nmStr)==false){
				alert(nmMsg);
				nmString.style.color = "red";
				nmString.focus();
				return false;
			}
			
			/*vetStr = nmString.value.split(".");
			if(vetStr[1].length>3 || vetStr[1].length<2) {
				alert(nmMsg);
				nmString.style.color = "red";
				nmString.focus();
				return false;
			}
			
			if(vetStr[2]!='' && vetStr[2]!='undefined'){
				if(vetStr[2].length!=2){
					alert(nmMsg);
					nmString.style.color = "red";
					nmString.focus();
					return false;
				}
			}*/
		}
	}

	/* ------------------------------------------------------------------------------------------- */
	
	/**
	 * Exige que uma string tenha um número mínimo de caracteres
	 * @param String
	 * @param Número mínimo
	 * @param Mensagem apropriada
	 */
	
	function nrMinCarac(nmString,nrMin,nmMsg){
		
		nmString = document.getElementById(nmString);
		
		if(nrMin<=0)
			nrMin = 5;
			
		nmMsg = "Você precisa digitar pelo menos "+nrMin+" caracteres no campo referente "+nmMsg;
			
		if(nmString.value.length<nrMin){
			alert(nmMsg);
			nmString.focus();
			return false;
		}
	
	}

	/* ------------------------------------------------------------------------------------------- */

	function confirmaDelDom(nmMsgUser){
		
		nmMsg 		= "OOOPS! Você está prestes a destruir configurações importantes do servidor!\n\n";
		
		if(nmMsgUser!='')
			nmMsg  += nmMsgUser;
			
		nmMsg 	   += " Deseja realmente fazer isso? Assume a responsabilidade pela exclusão?";
		fgConfirma  = confirm(nmMsg);
		
		return fgConfirma;
	}


	/* ------------------------------------------------------------------------------------------- */

	/**
	 * Pede confirmação para exclusão de domínios
	 * Mensagem disparada na exclusão
	 */
	function verificaDelDom(nmMsg){
	
		if(verificaChecked(document.frmExc)==true) {
			if(confirmaDelDom(nmMsg)==true){
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}
	/* ------------------------------------------------------------------------------------------- */

	/**
	 * Resume a escrita do código de window.open
	 */
	
	function abrePopUp(nmCaminho,nrLargura,nrAltura){	
		window.open('index.php?nmPag=popUp&nmArq='+nmCaminho+'','','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,fullscreen=no,resizable=yes,menubar=no,width='+nrLargura+',height='+nrAltura+'');	
	}

	/* ------------------------------------------------------------------------------------------- */

	/**
	 * Valida endereços de sites
	 * @param Id do campo a ser verificado
	 */
	
	function validaSite(nmId){		
		
		nrPtInval	= 0;
		str	 		= document.getElementById(nmId);
		validaPonto(nmId);
		
		// Coloca tudo em letras minúsculas
		str.value 	= str.value.toLowerCase();
		
		// Valida os tamanhos das partes				
		nrPt 		= str.value.indexOf(".");
		
		if(nrPt>=0){		
			vetSite 	= str.value.split("."); 
			nrPosConsul	= vetSite.length;
			nrTamConsul	= vetSite[nrPosConsul-1].length;
			
			if(nrPosConsul<2){
				nrPtInval++;
			}
			
			if(nrTamConsul<2 || nrTamConsul>4){
				nrPtInval++;
			}
			
		}
		
		// Bloqueia http://
		nrHttp		= str.value.indexOf("http");
		if(nrHttp>=0){
			str.value = str.value.replace("http","");
		}
		
		if(nrPtInval>0)
			return false;
		else 
			return true;
		
	}

	/* ------------------------------------------------------------------------------------------- */

	/**
	 * Bloqueia pontos nas primeiras e últimas posições
	 */
	function validaPonto(str){
		
		str 		= document.getElementById(str);
		// Verifica se tem dois pontos juntos
		fgDoisPt	= str.value.indexOf("..");		

		if(fgDoisPt>=0){
			str.value = str.value.replace("..",".");
		}
		
		// Verifica se a primeira  ou a última posição é um ponto
		nrTam		= str.value.length;
		fgPtIni     = str.value.substr(0,1);
		fgPtFim		= str.value.substr(nrTam-1,1);
		
		if(fgPtIni=='.')
			str.value = str.value.substr(1,nrTam);
		
		if(fgPtFim=='.')
			str.value = str.value.substr(0,nrTam-1);
		
	}

	/* ------------------------------------------------------------------------------------------- */
	
	/**
	 * Valida IP. inclusive no formato 192.168.1.1/24
	 */
	function validaIp(nmId){
			
		str 		= document.getElementById(nmId);
		validaPonto(nmId);
		
		fgPt		= str.value.indexOf(".");
		fgBloq		= 0;
		nrVoltas	= 0;
		
		if(fgPt>=0){
									
			vetIp   = str.value.split(".");
			
			for(d=0;d<vetIp.length;d++){
				
				if(vetIp[d]!='' && vetIp[d]!=undefined){
					
					nrVoltas++;
					nmIp  	= vetIp[d];
					nrIpInt = parseInt(nmIp);
					nrTamIp	= nmIp.length;
					
					if(d==0){						
						if(nrTamIp<1 || nrTamIp>3 || nrIpInt>254){
							fgBloq++;
						}						
					}					
					
					if(d==1 || d==2){
						if(nrIpInt>254 || (nrTamIp>3 || nrTamIp<1)){
							fgBloq++;
						}
					}
					
					if(d==3){
						
						fgBarra = nmIp.indexOf("/");
						if(fgBarra>=0){
							
							vetBarra = nmIp.split("/");
							nrIpInt	 = parseInt(vetBarra[0]);
							nrTamIp	 = nrIpInt.length;
							nrTamRed = vetBarra[1].length;
							
							if(nrTamRed>2){
								fgBloq++;
							}
						}
						
						if((nrTamIp>3 || nrTamIp<1)|| nrIpInt>254){
							fgBloq++;
						}
					}
					
					if(d>3){
						fgBloq++;
					}
				}				
			}
			
		} else {
			fgBloq++;
		}
		
		if(fgBloq>0 || nrVoltas<4)
			return false;
		else 
			return true;
	}
		

	/* ------------------------------------------------------------------------------------------- */

	/**
	 * Retorna navegador
	 */
	function navegador(){
		
		nmNavegador = "";
		
		if (window.XMLHttpRequest) {
			nmNavegador = "firefox";
		} else if (window.ActiveXObject) {
			nmNavegador = "ie";
		}
		
		return nmNavegador;
	}

	/* ------------------------------------------------------------------------------------------- */

	/**
	 * Organiza os formulários setando os tabindex corretamente para campos que estão habilitados e visíveis
	 */
	function organizaForm(idForm) {
			
		try {
			var f = document.getElementById(idForm);
			var numTabIndex = 1;        
		    
			for( var i = 0; i < f.elements.length; i++ ) {
				// Pegando o id
				idCampo = f.elements[i].id;
				
				campo = null;
				if (f.elements[i].type != 'hidden') {
					try {
						if (idCampo != '') {
							campo = document.getElementById(idCampo);
							if(campoDesbloqueado(campo)) {
								campo.tabIndex = numTabIndex;
								numTabIndex++;
							}
						}
					} catch(e){
					}
				}
			}
		} catch(e){
		}
		
		organizaFocus(idForm);
	}
	
	function campoDesbloqueado(campo) {

		if(campo.readOnly == true)
			return false;
	
		if(campo.disabled == true)
			return false;
	
		if(campo.style.visibility == 'hidden')
			return false;
		
	
		return true;
	
	}
	
	/**
	 * No IE existe um bug que após as chamadas em AJAX, se perde o foco da sequência dos tabindex.
	 * A função abaixo tenta setar os focus conforme o preenchimento dos campos para resolver esse bug.
	 */
	function organizaFocus(idForm){
	
		try {
			var f = document.getElementById(idForm);
	
			for( var i = 0; i < f.elements.length; i++ ) {
				// Pegando o id
				idCampo = f.elements[i].id;
				campo = null;
	
				if (f.elements[i].type != 'hidden') {
					try {
						campo = document.getElementById(idCampo);
						if(campoDesbloqueado(campo)) {							
							campo.focus();
							return false;
						}
					} catch(e){
					}
				}
			}
		} catch(e){
		}
	}
	
		
	function validaNum(evt, campo, aceitaDecimal) {   
		var key;
		if (window.event)     
			key = event.keyCode;
		else
			key = evt.which;
		
		if ( (key > 47 && key < 58) || (key > 95 && key < 106) || key == 8 || key == 9 || key == 35  || key == 36  || key == 37 || key == 39 || key == 46)
			return; // Se a tecla pressionada é número (0-9) ou backspace (8) não faz nada
		else if ((key == 110 || key == 188)&& campo.value.indexOf(",",0) == -1 && campo.value != "" && aceitaDecimal)
			return; // Se a tecla pressionada é vírgula (44) e o campo não está vazio e não possui outra vírgula e o campo aceita decimal não faz nada
		else // senão descarta a tecla pressionada
			if (window.event) //IE       
				window.event.returnValue = null;     
			else //Firefox       
				evt.preventDefault(); 
	}	
	
	
	
	function mostraEscondeMsg(idCampo, mostra){
		
		if (mostra) {
			document.getElementById(idCampo).style.visibility="visible"; 
		} else {
			document.getElementById(idCampo).style.visibility="hidden"; 
		}		
	}
	
	function fechaTempo(idCampo, tempo){
		tempo = Math.ceil(tempo);
		setTimeout("document.getElementById('"+idCampo+"').style.visibility='hidden'", tempo);
	}

/* ------------------------------------------------------------------------------------------- */

function formataData(idCampo){
        var campo;
        var tam;
        var valorCampoAux;
        
        if(idCampo != null) {
                campo = document.getElementById(idCampo);
                valorCampoAux = campo.value;
        }
        
        if(campo.value != null) {                
                                                
                // Completa o ano com "19", caso o usuário tenha informado ano com 2 dígitos.
                tam = campo.value.length;
                
                if(tam > 0) {
                    barra = campo.value.indexOf("/");
                    
                    if(barra >= 0) {
                            // Tem barra, então o campo tem que ter no mínimo 8 e no máximo 10 caracteres
                            if(tam == 8){
                                    digFinal = valorCampoAux.substr(tam-2, tam);
                                    digFinal = parseFloat(digFinal);
                                                                
                                    if(digFinal > 49){
                                        valorCampoAux = valorCampoAux.substr(0, tam-2) + "19" + valorCampoAux.substr(tam-2, tam);
                                    } else {
                                        valorCampoAux = valorCampoAux.substr(0, tam-2) + "20" + valorCampoAux.substr(tam-2, tam);
                                    }
                            } else {						
                                    if(tam != 10 && tam != 8){
                                            alert('Formato de data inválido!');
                                            return false;
                                    }
                            }
                    } else {
                            // Não tem barra, então o campo tem que ter no mínimo 6 e no máximo 8 dígitos.
                            if(tam == 6) {
                                    digFinal = valorCampoAux.substr(tam-2, tam);
                                    digFinal = parseFloat(digFinal);                                    
                                    
                                    if(digFinal > 49){
                                        valorCampoAux = valorCampoAux.substr(0, tam-2) + "19" + valorCampoAux.substr(tam-2, tam);
                                    } else {
                                        valorCampoAux = valorCampoAux.substr(0, tam-2) + "20" + valorCampoAux.substr(tam-2, tam);
                                    }
                            } else {
                                    if(tam != 8 && tam != 6){
                                            alert('Formato de data inválido!');
                                            return false;
                                    }
                            }
                            
                            // Coloca as barras
                            valorCampoAux = valorCampoAux.substr(0, 2) + "/" + valorCampoAux.substr(2, 2) + "/" + valorCampoAux.substr(4, 4);
                    }				
                    campo.value = valorCampoAux;
                } else {
                    return false;
                }
        }
        return true;
                        
}

/* ----------------------------------------------------------------------------------------------------------------------------------- */

function verificaData(Data) {

    var err = 0;
    var string;
    var valid = "0123456789/";
    var ok = "yes";

    if(Data != null) {
            
            if(!formataData(Data)) {				
                    return false;
            }
    
            try {
                    string = document.getElementById(Data).value;
            } catch(e) {                   
                    string = null;
            }				
    }
       
    if(string != null && string.length > 0) {
            
            for (var i=0; i<string.length; i++) {
                            var temp = "" + string.substring(i, i+1);
                            if (valid.indexOf(temp) == "-1") err = 1;
            }

            if (string.length != 10) err = 1;

            dia = string.substring(0, 2);
            barra1 = string.substring(2, 3);
            mes = string.substring(3, 5);   
            mes = parseFloat(mes);
            barra2 = string.substring(5, 6);
            ano = string.substring(6, 10);

            if ((dia < 1) || (dia > 31)) {               
                err = 1;
            }
            
            if (barra1 != '/') {    
                err = 1;
            }
            
           
            if ((mes < 1) || (mes > 12)) { 
                err = 1;
            }
            
            if (barra2 != '/') {
                err = 1;
            }
            
            if (ano < 0) {
                err = 1;
            }

            if (mes == 4 || mes == 6 || mes == 9 || mes == 11)
                    if (dia == 31) {
                           err = 1;
                    }

    
            if (mes == 2) {
                            var g = parseInt(ano/4);
                            if (isNaN(g)) err = 1;
                            if (dia > 29) err = 1;
                            if ((dia == 29) && (((ano/4) != parseInt(ano/4)))) err = 1;                            
            }

            if (err == 1) {								
                    alert('Data inválida!');
                    document.getElementById(Data).focus();
                    return false;
            } else {
                    return true;
            }
    }		
    return false;
}


function addFavoritos(){
	
	pagina = "http://www.camaranovapadua.com.br";
	titulo = "Câmara de Nova Pádua";
	descricao = "Câmara de Nova Pádua";

	// Gecko (Mozilla, Firefox, Firebird & Netscape)
	if(window.sidebar)document.write("<a href=\"javascript:window.sidebar.addPanel('"+titulo+"','"+pagina+"','');\"><img src=\"imagens/favoritos.gif\" border=\"0\"></a>");
	else
	// Internet Explorer
	if(window.external)document.write("<a href=\"javascript:window.external.AddFavorite('"+pagina+"','"+titulo+"');\"><img src=\"imagens/favoritos.gif\" border=\"0\"></a>");
	else
	// Opera & Outros
	document.write("<a href='"+pagina+"' rel='sidebar' title='"+titulo+"'>"+descricao+"</a>");

}









