function ltrim ( s )  { 
   return s.replace( /^\s*/, "" ) ;
} 

function rtrim ( s )  { 
   return s.replace( /\s*$/, "" ); 
} 


function trim ( s ) { 
   return rtrim(ltrim(s)); 
} 

function testaVazio(elemento, texto) {
  str = trim(elemento.value);
  if ((str=="") || (str.length==0) || (str=="Null")) {
	alert("Informe "+ texto + ".");
	elemento.focus();
	return false;
  }
  return true;
}

function testaTamanho(elemento, tam, texto) {
  str = elemento.value;
  if (str.length>tam) {
	alert(texto + " deve possuir no máximo " + tam +" caracteres.");
	elemento.focus();
	return false;
  }
  return true;
}

function validaTipoArquivo(objfile, extensions){
	var strfile = new String(objfile.value.toLowerCase());
	var arrext  = extensions.split(",");
	var test    = false;
	strfile     = strfile.substr((strfile.length-3), 3);
	for (i=0;i<arrext.length;i++){
		if ( parseInt( strfile.search(arrext[i]) ) != -1){
			test = true;
			break;
		}   
	}
	return test;
}

function validafoto(objfile){
	var test = true;
	if (objfile.value.length > 0) {
		test = false;
		if (!validaTipoArquivo(objfile,"gif,jpg,peg")){
			alert("O arquivo selecionado não é uma imagem válida.");
		}else{
			test = true;  
		}
	} 
	return test;
}

function validaTipoArquivo(objfile, extensions){
   var strfile = new String(objfile.value.toLowerCase());
   var arrext  = extensions.split(",");
   var test    = false;
   strfile     = strfile.substr((strfile.length-3), 3);
   //alert(strfile)
   for (i=0;i<arrext.length;i++){
   	   //alert(arrext[i].length)
       if ( parseInt( strfile.search(arrext[i]) ) != -1){
         test = true;
		 //alert(parseInt( strfile.search(arrext[i]) ))
         break;
       }   
   }

   return test;
}

function validaarquivo(objfile){
	var test = true;
	if (objfile.value.length > 0) {
	  test = false;
	  
		  if (validaTipoArquivo(objfile,"exe,com,bat,reg,vbs,pif,.js")){
		     //objfile.value = "";
		     alert("Por questão de segurança, não é permitido enviar arquivos executáveis.");
			 //objfile.focus()
		  }else{
		     test = true;  
		  }
	 }  
  return test;
}

function validaRadio(form,elemento,texto) {
	  var existe = false;
	  for (i=0; i<form.length;i++) {
		if (form.elements[i].name == elemento) {
		  if (form.elements[i].checked) {
		    existe=true;
		  }
		}
	  }
	  if (!existe) {
		alert('Selecione '+texto+'.');
		return false;
	  }else {
	  	return true;
	  }
}

//Formata o valor apos sair do campo
function ocMoeda(valor){
	if (valor.value.length != 0) {
		if((valor.value.indexOf(".") == -1) && (valor.value.indexOf(",") == -1)) valor.value = valor.value+",00";
		if (valor.value.indexOf(",") > -1){
			if (valor.value.indexOf(",") == (valor.value.length-1)) valor.value =  valor.value+"00";
			if (valor.value.indexOf(",") == (valor.value.length-2)) valor.value = valor.value+"0";
		}
		//Função que arredonda - Zeca - 
		if (valor.value.length > valor.value.indexOf(',')+3){
			valor.value = valor.value.substring(0,valor.value.indexOf(',')+1) + Math.round(valor.value.substring(valor.value.indexOf(",")+1, valor.value.indexOf(",")+3)+'.'+valor.value.substring(valor.value.indexOf(",")+4,valor.value.length ));
		}
	}
}


//===================================================================
		var Page_ConfirmationVer = "2.0";
		var MaxMes = new Array(31,31,29,31,30,31,30,31,31,30,31,30,31)
		netscape = "";
		ver = navigator.appVersion; len = ver.length;
		for(iln = 0; iln < len; iln++) if (ver.charAt(iln) == "(") break;
		netscape = (ver.charAt(iln+1).toUpperCase() != "C");

		function keyDown(DnEvents) { // handles keypress
		
			try { 
				// determines whether Netscape or Internet Explorer
				k = (netscape) ? DnEvents.which : window.event.keyCode;
			
				if (k == 13) { // enter key pressed
					if (nextfield == 'done' ) {
						return true; // submit, we finished all fields
						}
					else  { // we're not done yet, send focus to next box
						eval('document.Form1.' + nextfield + '.focus()');
						//eval('document.Form1.' + nextfield + '.select()');
						return false;
						
					}
				}
				
				
			}
			catch(e){
				return false;
			}	
			
		}

//*****
//***** Valida data		              		
//*****
function ValidaData(campo,mascara) { 
		var bolOK,intPos
		var j
		var dtData = new Date()
		var strDia,strMes,strAno,strHora,strMin,strSeg
		var strData,strDataTmp

		
		strData = campo.value;
		
		strDia = "";
		strMes = "";
		strAno = "";
		
		bolOK = true;
		
		if (strData.length > 0 ) {
			//Verifica Ano
			intPos = mascara.indexOf('y');

			if (intPos >=0 ) {
				strAno = strData.substr(intPos,4);	
				if (strAno == '') {
					strAno = dtData.getFullYear() ;
				}
				else {
					if (strAno.length < 4 ) {
						strAno = 2000 + parseInt(strAno);
						strAno = "" + strAno
					}
					else {
						if ( strAno < 1900 || strAno > 2999) {
							bolOK = false;
						}
					}
				}

			}

			//Verifica Mes
			intPos = mascara.indexOf('M');

                        if (intPos >=0 && bolOK == true) {
				strMes = strData.substr(intPos,2);
				if (strMes == '') { 
					strMes =  dtData.getMonth()+1 + "" ;
					if (strMes.length ==1) { strMes = "0" + strMes;}
				}	
				else {
					if (strMes < 1 || strMes > 12 ) {
						bolOK = false;	
					}
				
				}
			}

			//Verifica Dia
			intPos = mascara.indexOf('d');

                        if (intPos >=0 && bolOK == true) {
				strDia = strData.substr(intPos,2);
				if (strDia < 1 || strDia > MaxMes[parseInt(strMes)]) {
					bolOK = false;		
				}	
			}
				

			
			if (bolOK == false){
				
				alert("Data inválida!");
				campo.value = "";
	   			eval('document.formulario.' + campo.id + '.focus()');
	   			eval('document.formulario.' + campo.id + '.select()');
		   	
	   		}
	   		else { 
	   			strDataTmp="";
	   			strData ="";
	   			j = -1;
	   			strData += strDia;
	   			strData += strMes;
	   			strData += strAno;
	   			
	   			for(var i=0; i < mascara.length;i++) {
						if (mascara.substr(i,1) != '#' &&
							mascara.substr(i,1) != 'd' &&
							mascara.substr(i,1) != 'M' &&
							mascara.substr(i,1) != 'y' &&
							strDataTmp.length == mascara.substr(0,i).length ) {
							strDataTmp = strDataTmp + mascara.substr(i,1);
						}	
						else {
							j++;
							strDataTmp = strDataTmp + strData.substr(j,1);
						}
					campo.value = strDataTmp;
				}	
	   	
		}
			
}

		}				
			
		function FormataCampo(campo,mascara) { 
			var Texto,OldValue,j
			
			Texto = '';
			OldValue = campo.value;
			
			OldValue = RemoveMascara(OldValue);
			
			// Determina quando é Netscape ou Internet Explorer
			k = (netscape) ? DnEvents.which : window.event.keyCode;
						
			if (mascara.length == OldValue.length  ||  ((k < 48) || (k > 57)) ) {
				if (netscape) 
					DnEvents.which = 0 ;
				else
					window.event.keyCode = 0;
				return;	
			}
			
			campo.value = "";
			Texto = "";
			j = -1;
			
			for(var i=0; i < mascara.length;i++) {
					if (mascara.substr(i,1) != '#' &&
					   mascara.substr(i,1) != 'd' &&
					   mascara.substr(i,1) != 'M' &&
					   mascara.substr(i,1) != 'y' &&
					   Texto.length == mascara.substr(0,i).length ) {
							Texto = Texto + mascara.substr(i,1);
						}	
					else {
						j++;
						Texto = Texto + OldValue.substr(j,1);
					}
						
					
			}
			campo.value = Texto;

		}
						
		function RemoveMascara(Texto){
		var j,Car
		
		j = 0;
		//
		//Remove caracteres especiais da mascara
		//
		while (j < Texto.length) {
			Car = Texto.substr(j,1)
			if (Car >= 0 && Car <= 9) {
			   j++;
			}
			else {
				Texto = Texto.replace(Car, "" );
			}
		}
		
		return Texto;
		}
				
function ConfirmationOnLoad() {
    if ( !ConfirmationBrowserCapable() ) return;
    if (typeof(Page_Confirmations) == "undefined") return;
    var i, confirmButton;
    for (i = 0; i < Page_Confirmations.length; i++) {
        confirmButton = Page_Confirmations[i];
        if (typeof(confirmButton) == "string") {
            confirmButton = document.getElementById( confirmButton );
        }
        if ( typeof(confirmButton.confirmationmessage ) == "undefined" ) {
            if ( typeof( confirmButton.attributes ) != "undefined" ) {
                confirmButton.confirmationmessage = confirmButton.attributes["confirmationmessage"].value;
            } else {
                confirmButton.confirmationmessage = "Are you sure you want to do this?";
            }
        }
        ConfirmationHookupControl(confirmButton);
    }
}

function ConfirmationBrowserCapable() {
    if ( typeof( document.getElementById ) == "undefined" ) {
        if( typeof( document.all ) != "undefined" ) {
            document.getElementById = function( elementId ) { return document.all[elementId]; };
            return true;
        }
        return false;
    }
    return true;
}

//*****
//***** Valida e-mail
//*****
function testaEmail(txtInput) {
	var email = txtInput.value;
	var proibido;
	var checkMail;
	
	//define os proíbidos
	proibido = " +)(*&%$#,!+;='\/`[]~?<>áéíóúýàèìòùäëïöüÿçãõâêîôû£¢¬§³²¹´";
	
	//testa se é vazio
	if (email == "") {
		alert("Informe um e-mail.");
		txtInput.focus();
		return false;
	} else {
  		if ((email.indexOf('@') == email.lastIndexOf('@')) &&	// só tem um @
  			(email.indexOf('@') > 0) &&			// existe @ e não é prim
  			(email.charAt(email.length-1) != '@') &&		// @ não é o último
  			(email.lastIndexOf('.') > email.indexOf('@')) &&	// existe . após @
  			(email.charAt(email.indexOf('@') + 1) != '.') &&	// sem . logo após @
  			(email.charAt(email.indexOf('@') - 1) != '.') &&	// sem . logo antes @
  			(email.indexOf('.') > 0) &&			// existe . e não é prim
			(email.charAt(email.length-1) != '.')) {		// . não é o último
				
			// verifica se não há pontos seguidos
			sub = email.substring(email.indexOf('.')+1, email.length);
			while (sub.indexOf('.') != -1) {
				if (sub.charAt(0) == '.') {
					alert("Formato de e-mail incorreto!");
					txtInput.focus();
					return false;
				} else {
					sub = sub.substring(sub.indexOf('.')+1, sub.length);
				}
			}
			//return true;

			for(c=0;c<email.length;c++){
				for (j=0; j<proibido.length;j++){
					if (proibido.charAt(j)==email.charAt(c)){
						alert ("Caracteres inválidos no e-mail");
						checkMail = false;
						return false;
					}
				}
			}
			if (checkMail==false) {
				return false;
			} else {
				return true;
			}

		} else {
			alert("Formato de e-mail incorreto!");
			txtInput.focus();
			return false;
		}
	}
}

