function trim(aStr) {
return aStr.replace(/^\s{1,}/, "").replace(/\s{1,}$/, "")
}
    
/*********************************************************
Set of JavaScript functions used to validate forms

JavaScript Validation 2.0, 23/Nov/2000
Jake Howlett, http://www.codestore.net/

**********************************************************/
function blockChars (field, evt, vet) {
	var keyCode = evt.which ? evt.which : evt.keyCode;  
	for (var i=0; i < vet.length; i++)
	if ( vet[i] == keyCode ) return false;
	return true;
}    
		
function validateNumber (field, evt, allowDecimal) {
	if (allowDecimal==undefined) allowDecimal = true;
	var keyCode = evt.which ? evt.which : evt.keyCode; 
	var vet = new Array (8, 9, 32, 35, 46, 36, 37, 39, 111, 223);
	if ( allowDecimal ) {
		vet.push(188);vet.push(189);vet.push(110);
	}
	if (keyCode >= 48 && keyCode < 59 || keyCode >= 96 && keyCode <= 105)    return true;
	if (keyCode == 13)  return tabOnEnter (field,evt);
	for (var i=0; i < vet.length; i++)
	if ( vet[i] == keyCode ) return true;
	return false;
}

function validateNonNumber (field, evt) {
	var keyCode = evt.which ? evt.which : evt.keyCode;  
	if (keyCode >= 48 && keyCode < 59 || keyCode >= 96&& keyCode < 105)   return false;
	if (keyCode == 13)  return tabOnEnter (field,evt);
}

function skip () { this.blur(); }
    
function disableTextField (field) {
	if (document.all || document.getElementById) 
		field.disabled = true;
	else {
		field.oldOnFocus = field.onfocus;
		field.onfocus = skip;
	}
}
    
function enableTextField (field) {
	if (document.all || document.getElementById)
		field.disabled = false;
	else {
		field.onfocus = field.oldOnFocus;
	}
}
    
function getNextElement (field) {
	var form = field.form;
	for (var e = 0; e < form.elements.length; e++)
	if (field == form.elements[e])
	break;
	return form.elements[++e % form.elements.length];
}
    
function tabOnEnter (field, evt) {
	var keyCode = document.layers ? evt.which : document.all ? 
	evt.keyCode : evt.keyCode;
	if (keyCode != 13)
		return true;
	else {
		if (getNextElement(field).readOnly!=true){
			getNextElement(field).focus();
		}
		return false;
	}
}
    
var symbols = " !\"#$%&'()*+'-./0123456789();<=>?@";

function toAscii (field)  {
	var loAZ = "abcdefghijklmnopqrstuvwxyz";
	symbols+= loAZ.toUpperCase();
	symbols+= "[\\]^_`";
	symbols+= loAZ;
	symbols+= "{|}~";
	var loc;
	loc = symbols.indexOf(field.value);
	if (loc >-1) { 
		Ascii_Decimal = 32 + loc;
		return (32 + loc);
	} 
   return(0);  // If not in range 32-126 return ZERO
}
    
/***********************************************************
DateComponents()
This function splits a date in to the day, month and year 
components, depending on the format supplied. Used by Date 
Validation routine.
Arguments:
obj = Input whose value is to be checked
format = date format, ie mm/dd or dd/mm
************************************************************/
function DateComponents(dateStr, format) {
	var results = new Array();
	var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{2}|\d{4})$/;
	var matchArray = dateStr.match(datePat);
	if (matchArray == null) { 
		return null; 
	}
	//check for two digit (20th century) years and prepend 19.
	matchArray[4] = (matchArray[4].length == 2) ? '19' + matchArray[4] : matchArray[4];
	// parse date into variables
	if (format.charAt(0)=="d"){ //what format does the server use for dates? 
		results[0] = matchArray[1];
		results[1] = matchArray[3];
	} else { 
		results[1] = matchArray[1];
		results[0] = matchArray[3]; 
	}
	results[2] = matchArray[4];
	return results;
}

 /***********************************************************
 valiDate()
 This function checks that the value of a date is in the 
 correct format and, optionally, within a certain range.
 Arguments:
 obj = Input whose value is to be checked
 min = Optional minimum allowed value
 max = Optional maximum allowed value
 format = date format, ie mm/dd or dd/mm
 ************************************************************/
function ValiDate(obj, min, max, format){
	dateBits = DateComponents(obj.value, format);
	if (dateBits == null) return false;
	//Check it is a valid date first
	day = dateBits[0];
	month = dateBits[1];
	year = dateBits[2];
	if ((month < 1 || month > 12) || (day < 1 || day > 31)) { // check month range 
		return false;
	} 
	if ((month==4 || month==6 || month==9 || month==11) && day==31) {
		return false;
	}
	if (month == 2) {
		// check for february 29th 
		var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)); 
		if (day>29 || (day==29 && !isleap)) {
			return false;
		}
	} 	  
	//Now check whether a range is specified and if in bounds
	var theDate = new Date(dateBits[2], parseInt(dateBits[1]) - 1, dateBits[0]);   
	if ( min ) {
		minBits = DateComponents (min, format);
		var minDate = new Date(minBits[2], parseInt(minBits[1]) - 1, minBits[0]);
		if ( minDate.getTime() > theDate.getTime() ) return false;
	} 
	if ( max) {
		maxBits = DateComponents (max, format);
		var maxDate = new Date(maxBits[2], parseInt(maxBits[1]) - 1, maxBits[0]);
		if ( theDate.getTime() > maxDate.getTime() ) return false;
	}
	return true;
}
    
    
    function ValidateEmail (f) {
    var emailStr = trim(f.value);
    
    if (emailStr=='') return true;
    /* Pattern to check if the entered e-mail address fits the user@domain format. */
    var emailPat=/^(.+)@(.+)$/
    
    /* Pattern to check for special characters we don't want, including ( ) < > @ , ; : \ " . [ ] */
    var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
    
    /* The following string represents the range of characters allowed in a username or domainname */
    var validChars="\[^\\s" + specialChars + "\]"
    
    /* The following pattern applies if the "user" is a quoted string, E.g. "jiminy cricket"@disney.com */
    var quotedUser="(\"[^\"]*\")"
    
    /* Pattern for domains that are IP addresses, rather than symbolic names. E.g. joe@[123.124.233.4] is a legal e-mail address. NOTE: The square brackets are required. */
    var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
    
    /* The following string represents an atom (basically a series of non-special characters.) */
    var atom=validChars + '+'
    
    /* The following string represents one word in the typical username. For example, in john.doe@themorgue.hell, john and doe are words */
    var word="(" + atom + "|" + quotedUser + ")"
    
    // The following pattern describes the structure of the user
    var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
    
    /* The following pattern describes the structure of a normal symbolic domain, as opposed to ipDomainPat, shown above. */
    var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")
    
    /* Finally, let's start trying to figure out if the supplied address is valid. */
    
    /* Begin with the coarse pattern to simply break up user@domain into different pieces that are easy to analyze. */
    
    var matchArray=emailStr.match(emailPat)
    if (matchArray==null) {
      /* Too many/few @'s or something; basically, this address doesn't even fit the general mould of a valid e-mail address. */
      alert("O Email está incorreto (verifique @ e .'s)")
      f.focus();
      return false;
    }
    var user=matchArray[1]
    var domain=matchArray[2]
    
    // See if "user" is valid 
    if (user.match(userPat)==null) {
      // user is not valid
      alert("O nome do usuário é inválido.")
      return false
      f.focus();
    }
    
    /* if the e-mail address is at an IP address make sure the IP address is valid. */
    var IPArray=domain.match(ipDomainPat)
    if (IPArray!=null) {
    // this is an IP address
    for (var i=1;i<=4;i++) {
      if (IPArray[i]>255) {
        alert("O IP é inválido!")
        f.focus();
        return false;    
      }
    }
    return true
    }
    
    // Domain is symbolic name
    var domainArray=domain.match(domainPat)
    if (domainArray==null) {
      alert("O domínio é inválido!")
      f.focus();
      return false;
    }
    
    /* domain name seems valid, but now make sure that it ends in a three-letter word (like com, edu, gov) or a two-letter word, representing country (uk, nl), and that there's a hostname preceding the domain or country. */
    
    /* Now we need to break up the domain to get a count of how many atoms it consists of. */
    var atomPat=new RegExp(atom,"g")
    var domArr=domain.match(atomPat)
    var len=domArr.length
    if (domArr[domArr.length-1].length<2 || domArr[domArr.length-1].length>3) {
    // the address must end in a two letter or three letter word.
      alert("O endereço deve terminar como três letras do domínio\nou duas letras do país.")
      f.focus();
      return false;  
    }
    
    // Make sure there's a host name preceding the domain.
    if (len<2) {
    var errStr="O email não possui o HostName"
      alert(errStr)
      f.focus();
      return false;
    }
    
    // If we've gotten this far, everything's valid!
    //alert(emailStr + ' seems to be a valid address!');
    return true;
    }
    
    /***********************************************************
    ValidateFileType()
    This function checks that the type of file being uploaded
    is allowed
    Arguments:
    obj = The File Upload control.
    fTyp = Allowed file types
    ************************************************************/
    
    function ValidateFileType( obj, fTyp ) {
    
    dots = obj.value.split(".");
    fType = "." + dots[dots.length-1];
    
    if ( fTyp != null && fTyp.indexOf(fType) == -1 ) return false;
    
    return true;
    }
    
    
    /***********************************************************
    ValidateFileLimit()
    This function checks that the value in a file upload
    Arguments:
    obj = The File Upload control
    cur = Current number of file attachments
    max = Limit on allowed files
    ************************************************************/
    
    function ValidateFileLimit( obj, cur, max ) {
    
    if ( cur >= max ) return false;
    
    return true;
    }
    
    
    /***********************************************************
    OnFailure()
    This function returns the failure message to the user and
    sets focus on the input in question.
    Arguments:
    obj = Input element on which to return focus
    lbl = Field Label to prepend on to the message
    msg = Array value for message to give the user
    ************************************************************/
    
    function valid (obj,errMsg) {
    
     var isFilled = false;
     var objFocus;
     // Verifico o tipo de objeto para determinar o teste de obrigatoriedade
    objFocus = obj;
    var objLen = obj.length;
    if (obj.type == 'text' || obj.type == 'textarea' || obj.type == 'password') {
           if (obj.value.length > 0 )  isFilled = true;		   
    }else if ( obj.type == 'select-one' ) { 
             if (obj.options[obj.selectedIndex].text.charAt(0)!='-') 
    				     isFilled = true;
    }else {
    		   objFocus = obj[0];
           for (i=0; i < objLen; i++) {
              if (obj[i].checked) {
    					   isFilled = true;
    						 break;
    					}	 
    			 }			
     }		 
    
     if (!isFilled) {
        alert( errMsg );
        objFocus.focus();	  
        return false;
     }  
    return true;
    }
    
    function OnFailure( obj, lbl, msg ){
    	var msgs = new Array();
    	msgs["text"] = " deve ser informado(a). \nFavor entrar com um valor.";
    	msgs["password"] = " deve ser informado(a). \nFavor entrar com um valor.";	
    	msgs["textarea"] = " deve ser informado(a). \nFavor entrar com um valor.";
    	msgs["select-one"] = " deve ser informado(a). \nFavor selecionar uma opção.";
    	msgs["select-multiple"] = " deve ser informado(a). \nFavor selecionar uma opção.";
    	msgs["checkbox"] = " deve ser informado(a). \nFavor selecionar uma opção.";
    	msgs["file"] = " deve ser informado(a). \nFavor selecionar o arquivo.";
    	msgs["fileType"] = " requires certain file types. \nFavor selecionar a valid file type.";
    	msgs["fileLimit"] = " is a limited file upload. \nPlease reduce number of attachment(s) first.";
    	msgs["radio"] = " deve ser informado(a). \nFavor selecionar uma opção.";
    	msgs["number"] = " é um campo numérico. \nFavor infomar um número válido.";
    	msgs["date"] = " é um campo data. \nFavor informar uma data válida..";
    	msgs["email"] = " é um campo email. \nFavor informar um email válido.";
    	msgs["cpf"] = " é um CPF inválido. \nFavor informar um cpf válido.";	
    	 
    	if(msg[1]	|| msg[2]){ //upper/lower bound ranges have been specified
    		if(msg[1]	&& msg[2]){//range
    			term = ( msg[0] == "date" )? " ("+msg[3]+")" : "";
    			alert(lbl + msgs[msg[0]] + term + " between " + msg[1] + " and " + msg[2]);
    		} else if (msg[1]) {//lower bound
    			term = ( msg[0] == "number" ) ? " greater than " : " (" + msg[3] + ") after ";
    			alert(lbl + msgs[msg[0]] + term + msg[1]);
    		} else {//upper bound
    			term = ( msg[0] == "number" )? " less than " : " (" + msg[3] + ") before ";
    			alert(lbl + msgs[msg[0]] + term + msg[2]);
    		}
    	} else {//no range given
    		alert(lbl + msgs[msg[0]]);
    	}
    	
    	obj.focus();
    	return false;
    }
    
    
    /***********************************************************
    isSomethingSELECTED()
    This function is passed an object of type redio group or check
    box. It then loops through all options and checks that 
    one of them is SELECTED, returning true if so.
    Arguments:
    obj = Reference to the parent object of the group.
    ************************************************************/
    
    function isSomethingSELECTED( obj ){
    	for (var r=0; r < obj.length; r++){
    		if ( obj[r].checked ) return true;
    	}
    }
    
    
    /***********************************************************
    validateRequiredFields()
    This function is passed an array of fields that are required
    to be filled in and iterates through each ensuring they have
    been correctly entered.
    ************************************************************/
    
    function validateRequiredFields( f, a ){
    
    	for (var i=0; i < a.length; i++){
    		e = a[i][0];
    			//checks input types: "text","select-one","select-multiple","textarea","checkbox","radio","file"
    			try {
    				switch (e.type) {
    					case "text":
    							if ( trim(e.value) == "" ) return OnFailure(e, a[i][1], ["text"]);
    						break
    					case "file":
    							if ( trim(e.value) == "" ) return OnFailure(e, a[i][1], ["file"]);
    						break							
    					case "password":
    							if ( trim(e.value) == "" ) return OnFailure(e, a[i][1], ["text"]);
    						break							
    					case "textarea":
    					if ( trim(e.value) == "" ) return OnFailure(e, a[i][1], ["textarea"]);
    						break
    					case "select-one":
    					if ( e.selectedIndex == 0 ) return OnFailure(e, a[i][1], ["select-one"]);
    						break
    					case "select-multiple":
    					if (e.selectedIndex == -1) return OnFailure(e, a[i][1], ["select-multiple"]);
    						break
    					case "cpf":
    					 if ( !check_cpf(trim(e.value)) ) return OnFailure(e, a[i][1], ["text"]);
    					case "hidden":
    					   break
    					default:
    						//must be a checkbox or a radio group if none of above
    						switch (e[0].type) {
    								case "checkbox":
    								if ( !isSomethingSELECTED( e ) )  return OnFailure(e[0], a[i][1], ["checkbox"]);
    							break
    							case "radio":
    								if ( !isSomethingSELECTED( e ) )  return OnFailure(e[0], a[i][1], ["radio"]);
    								break
    								default:
    									break
    							}
    						break
    				}				
    		}catch (err) {
    		   alert ('ERRO: Ocorreu um erro na validação de campos\n'+err.description);
    			 return false;
    		}		
    	}
    	return true;
    }
    
    
    function check_cpf (cpf)
    {
      var v = cpf.value;
    	x = 0;
    	soma = 0;
    	dig1 = 0;
    	dig2 = 0;
    	texto = "";
    	numcpf1 = "";
    	len = v.length; x = len -1;
    	// var numcpf = "12345678909";
    	for (var i=0; i <= len - 3; i++) {
    		y = v.substring(i,i+1);
    		soma = soma + ( y * x);
    		x = x - 1;
    		texto = texto + y;
    	}
    	dig1 = 11 - (soma % 11);
    	if (dig1 == 10) dig1=0 ;
    	if (dig1 == 11) dig1=0 ;
    	numcpf1 = v.substring(0,len - 2) + dig1 ;
    	x = 11; soma=0;
    	for (var i=0; i <= len - 2; i++) {
    		soma = soma + (numcpf1.substring(i,i+1) * x);
    		x = x - 1;
    	}
    	dig2= 11 - (soma % 11);
    	if (dig2 == 10) dig2=0;
    	if (dig2 == 11) dig2=0;
    	//alert ("Digito Verificador : " + dig1 + "" + dig2);
    	if ((dig1 + "" + dig2) == v.substring(len,len-2)) {
    		return true;
    	}
    	alert ("Numero do CPF invalido !!!");
    	cpf.select();
    	return false;
    }
    
    // ****************************************************************
    // Valida CNPJ
    // ****************************************************************
    
    		function check_cnpj(f)
    		{
    		  var CNPJ = f.value;
    			var total,total1,dv,dv1
    			if (CNPJ.length == 14)
    			{
    				total = (CNPJ.substring(0,1) * 5) + (CNPJ.substring(1,2)* 4) + (CNPJ.substring(2,3)* 3) +
    				(CNPJ.substring(3,4) * 2) + (CNPJ.substring(4,5)* 9) +
    				(CNPJ.substring(5,6) * 8) + (CNPJ.substring(6,7)* 7) +
    				(CNPJ.substring(7,8) * 6) + (CNPJ.substring(8,9)* 5) +
    				(CNPJ.substring(9,10) * 4) + (CNPJ.substring(10,11)* 3) +
    				(CNPJ.substring(11,12) * 2);
    
    				dv = 11 - (total%11);
    
    	
    				if (dv == 10 || dv == 11)
    				{
    					dv = 0;
    				}
    
    				if (dv != CNPJ.substring(12,13))
    				{
    					total1 = (CNPJ.substring(0,1) * 6) + (CNPJ.substring(1,2)* 5) + (CNPJ.substring(2,3) * 4) +
    					(CNPJ.substring(3,4) * 3) + (CNPJ.substring(4,5)* 2) +
    					(CNPJ.substring(5,6) * 9) + (CNPJ.substring(6,7)* 8) +
    					(CNPJ.substring(7,8) * 7) + (CNPJ.substring(8,9)* 6) +
    					(CNPJ.substring(9,10) * 5) + (CNPJ.substring(10,11)* 4) +
    					(CNPJ.substring(11,12)* 3) + (CNPJ.substring(12,13) * 2);
    					
    					dv1 = 11 - (total1%11);
    					
    					if (dv1 == 10 || dv1 == 11)
    					{
    						dv1 = 0;
    					} 
    					 
    					if (dv1 != CNPJ.substring(13,14))
    					{
    					  f.select();
    						return false ;
    					}
    				}
    
    			}
    			else
    			{
    			  f.select();
    				return false;
    			}
    		  return true;
    		}
    
    
    <!-- Begin
    // Check browser version
    var isNav4 = false, isNav5 = false, isIE4 = false
    var strSeperator = "/"; 
    // If you are using any Java validation on the back side you will want to use the / because 
    // Java date validations do not recognize the dash as a valid date separator.
    var vDateType = 3; // Global value for type of date format
    //                1 = mm/dd/yyyy
    //                2 = yyyy/dd/mm  (Unable to do date check at this time)
    //                3 = dd/mm/yyyy
    var vYearType = 4; //Set to 2 or 4 for number of digits in the year for Netscape
    var vYearLength = 2; // Set to 4 if you want to force the user to enter 4 digits for the year before validating.
    var err = 0; // Set the error code to a default of zero
    if(navigator.appName == "Netscape") {
    if (navigator.appVersion < "5") {
    isNav4 = true;
    isNav5 = false;
    }
    else
    if (navigator.appVersion > "4") {
    isNav4 = false;
    isNav5 = true;
       }
    }
    else {
    isIE4 = true;
	
    }
    function DateFormat(vDateName, vDateValue, e, dateCheck, dateType) {
    vDateType = dateType;
    // vDateName = object name
    // vDateValue = value in the field being checked
    // e = event
    // dateCheck 
    // True  = Verify that the vDateValue is a valid date
    // False = Format values being entered into vDateValue only
    // vDateType
    // 1 = mm/dd/yyyy
    // 2 = yyyy/mm/dd
    // 3 = dd/mm/yyyy
    //Enter a tilde sign for the first number and you can check the variable information.
	
    if (vDateValue == "~") {
      alert("AppVersion = "+navigator.appVersion+" \nNav. 4 Version = "+isNav4+" \nNav. 5 Version = "+isNav5+" \nIE Version = "+isIE4+" \nYear Type = "+vYearType+" \nDate Type = "+vDateType+" \nSeparator = "+strSeperator);
      vDateName.value = "";
      vDateName.focus();
      return true;
    }
    var whichCode = (window.Event) ? e.which : e.keyCode;
	
    // Check to see if a seperator is already present.
    // bypass the date if a seperator is present and the length greater than 8
    if (vDateValue.length > 8 && isNav4) {
    if ((vDateValue.indexOf("-") >= 1) || (vDateValue.indexOf("/") >= 1))
    return true;
    }
    //Eliminate all the ASCII codes that are not valid
    var alphaCheck = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/-";
    if (alphaCheck.indexOf(vDateValue) >= 1) {
    if (isNav4) {
    vDateName.value = "";
    vDateName.focus();
    vDateName.select();
    return false;
    }
    else {
    vDateName.value = vDateName.value.substr(0, (vDateValue.length-1));
    return false;
       }
    }
    if (whichCode == 8) //Ignore the Netscape value for backspace. IE has no value
        return false;
    else {
    //Create numeric string values for 0123456789/
    //The codes provided include both keyboard and keypad values
    var strCheck = '47,48,49,50,51,52,53,54,55,56,57,58,59,95,96,97,98,99,100,101,102,103,104,105';
	
    if (strCheck.indexOf(whichCode) != -1) {
    if (isNav4) {
    if (((vDateValue.length < 6 && dateCheck) || (vDateValue.length == 7 && dateCheck)) && (vDateValue.length >=1)) {
    alert("Data Inválida\nFavor informar novamente");
    vDateName.value = "";
    vDateName.focus();
    vDateName.select();
    return false;
    }
    if (vDateValue.length == 6 && dateCheck) {
    var mDay = vDateName.value.substr(2,2);
    var mMonth = vDateName.value.substr(0,2);
    var mYear = vDateName.value.substr(4,4)
    //Turn a two digit year into a 4 digit year
    if (mYear.length == 2 && vYearType == 4) {
    var mToday = new Date();
    //If the year is greater than 30 years from now use 19, otherwise use 20
    var checkYear = mToday.getFullYear() + 30; 
    var mCheckYear = '20' + mYear;
    if (mCheckYear >= checkYear)
    mYear = '19' + mYear;
    else
    mYear = '20' + mYear;
    }
    var vDateValueCheck = mMonth+strSeperator+mDay+strSeperator+mYear;
    if (!dateValid(vDateValueCheck)) {
    alert("Data Inválida\nFavor informar novamente");
    vDateName.value = "";
    vDateName.focus();
    vDateName.select();
    return false;
    }
    return true;
    }
    else {
    // Reformat the date for validation and set date type to a 1
    if (vDateValue.length >= 8  && dateCheck) {
    if (vDateType == 1) // mmddyyyy
    {
    var mDay = vDateName.value.substr(2,2);
    var mMonth = vDateName.value.substr(0,2);
    var mYear = vDateName.value.substr(4,4)
    vDateName.value = mMonth+strSeperator+mDay+strSeperator+mYear;
    }
    if (vDateType == 2) // yyyymmdd
    {
    var mYear = vDateName.value.substr(0,4)
    var mMonth = vDateName.value.substr(4,2);
    var mDay = vDateName.value.substr(6,2);
    vDateName.value = mYear+strSeperator+mMonth+strSeperator+mDay;
    }
    if (vDateType == 3) // ddmmyyyy
    {
    var mMonth = vDateName.value.substr(2,2);
    var mDay = vDateName.value.substr(0,2);
    var mYear = vDateName.value.substr(4,4)
    vDateName.value = mDay+strSeperator+mMonth+strSeperator+mYear;
    }
    //Create a temporary variable for storing the DateType and change
    //the DateType to a 1 for validation.
    var vDateTypeTemp = vDateType;
    vDateType = 1;
    var vDateValueCheck = mMonth+strSeperator+mDay+strSeperator+mYear;
    if (!dateValid(vDateValueCheck)) {
    alert("Data Inválida\nFavor informar novamente");
    vDateType = vDateTypeTemp;
    vDateName.value = "";
    vDateName.focus();
    vDateName.select();
    return false;
    }
    vDateType = vDateTypeTemp;
    return true;
    }
    else {
    if (((vDateValue.length < 8 && dateCheck) || (vDateValue.length == 9 && dateCheck)) && (vDateValue.length >=1)) {
    alert("Data Inválida\nFavor informar novamente");
    vDateName.value = "";
    vDateName.focus();
    vDateName.select();
    return false;
             }
          }
       }
    }
    else {
    // Non isNav Check
    if (((vDateValue.length < 8 && dateCheck) || (vDateValue.length == 9 && dateCheck)) && (vDateValue.length >=1)) {
    alert("Data Inválida\nFavor informar novamente");
    vDateName.value = "";
    vDateName.focus();
    return true;
    }
    // Reformat date to format that can be validated. mm/dd/yyyy
    if (vDateValue.length >= 8 && dateCheck) {
    // Additional date formats can be entered here and parsed out to
    // a valid date format that the validation routine will recognize.
    if (vDateType == 1) // mm/dd/yyyy
    {
    var mMonth = vDateName.value.substr(0,2);
    var mDay = vDateName.value.substr(3,2);
    var mYear = vDateName.value.substr(6,4)
    }
    if (vDateType == 2) // yyyy/mm/dd
    {
    var mYear = vDateName.value.substr(0,4)
    var mMonth = vDateName.value.substr(5,2);
    var mDay = vDateName.value.substr(8,2);
    }
    if (vDateType == 3) // dd/mm/yyyy
    {
    var mDay = vDateName.value.substr(0,2);
    var mMonth = vDateName.value.substr(3,2);
    var mYear = vDateName.value.substr(6,4)
    }
    if (vYearLength == 4) {
    if (mYear.length < 4) {
    alert("Data Inválida\nFavor informar novamente");
    vDateName.value = "";
    vDateName.focus();
    return true;
       }
    }
    // Create temp. variable for storing the current vDateType
    var vDateTypeTemp = vDateType;
    // Change vDateType to a 1 for standard date format for validation
    // Type will be changed back when validation is completed.
    vDateType = 1;
    // Store reformatted date to new variable for validation.
    var vDateValueCheck = mMonth+strSeperator+mDay+strSeperator+mYear;
    if (mYear.length == 2 && vYearType == 4 && dateCheck) {
    //Turn a two digit year into a 4 digit year
    var mToday = new Date();
    //If the year is greater than 30 years from now use 19, otherwise use 20
    var checkYear = mToday.getFullYear() + 30; 
    var mCheckYear = '20' + mYear;
    if (mCheckYear >= checkYear)
    mYear = '19' + mYear;
    else
    mYear = '20' + mYear;
    vDateValueCheck = mMonth+strSeperator+mDay+strSeperator+mYear;
    // Store the new value back to the field.  This function will
    // not work with date type of 2 since the year is entered first.
    if (vDateTypeTemp == 1) // mm/dd/yyyy
    vDateName.value = mMonth+strSeperator+mDay+strSeperator+mYear;
    if (vDateTypeTemp == 3) // dd/mm/yyyy
    vDateName.value = mDay+strSeperator+mMonth+strSeperator+mYear;
    } 
    if (!dateValid(vDateValueCheck)) {
    alert("Data Inválida\nFavor informar novamente");
    vDateType = vDateTypeTemp;
    vDateName.value = "";
    vDateName.focus();
    return true;
    }
    vDateType = vDateTypeTemp;
    return true;
    }
    else {
    if (vDateType == 1) {
    if (vDateValue.length == 2) {
    vDateName.value = vDateValue+strSeperator;
    }
    if (vDateValue.length == 5) {
    vDateName.value = vDateValue+strSeperator;
       }
    }
    if (vDateType == 2) {
    if (vDateValue.length == 4) {
    vDateName.value = vDateValue+strSeperator;
    }
    if (vDateValue.length == 7) {
    vDateName.value = vDateValue+strSeperator;
       }
    } 
    if (vDateType == 3) {
    if (vDateValue.length == 2) {
    vDateName.value = vDateValue+strSeperator;
    }
    if (vDateValue.length == 5) {
    vDateName.value = vDateValue+strSeperator;
       }
    }
    return true;
       }
    }
    if (vDateValue.length == 10&& dateCheck) {
    if (!dateValid(vDateName)) {
    // Un-comment the next line of code for debugging the dateValid() function error messages
    //alert(err);  
    alert("Data Inválida\nFavor informar novamente");
    vDateName.focus();
    vDateName.select();
       }
    }
    return false;
    }
    else {
    // If the value is not in the string return the string minus the last
    // key entered.
    if (isNav4) {
    vDateName.value = "";
    vDateName.focus();
    vDateName.select();
    return false;
    }
    else
    {
    vDateName.value = vDateName.value.substr(0, (vDateValue.length-1));
    return false;
             }
          }
       }
    }
    function dateValid(objName) {
    var strDate;
    var strDateArray;
    var strDay;
    var strMonth;
    var strYear;
    var intday;
    var intMonth;
    var intYear;
    var booFound = false;
    var datefield = objName;
    var strSeparatorArray = new Array("-"," ","/",".");
    var intElementNr;
    // var err = 0;
    var strMonthArray = new Array(12);
    strMonthArray[0] = "Jan";
    strMonthArray[1] = "Feb";
    strMonthArray[2] = "Mar";
    strMonthArray[3] = "Apr";
    strMonthArray[4] = "May";
    strMonthArray[5] = "Jun";
    strMonthArray[6] = "Jul";
    strMonthArray[7] = "Aug";
    strMonthArray[8] = "Sep";
    strMonthArray[9] = "Oct";
    strMonthArray[10] = "Nov";
    strMonthArray[11] = "Dec";
    //strDate = datefield.value;
    strDate = objName;
    if (strDate.length < 1) {
    return true;
    }
    for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++) {
    if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1) {
    strDateArray = strDate.split(strSeparatorArray[intElementNr]);
    if (strDateArray.length != 3) {
    err = 1;
    return false;
    }
    else {
    strDay = strDateArray[0];
    strMonth = strDateArray[1];
    strYear = strDateArray[2];
    }
    booFound = true;
       }
    }
    if (booFound == false) {
    if (strDate.length>5) {
    strDay = strDate.substr(0, 2);
    strMonth = strDate.substr(2, 2);
    strYear = strDate.substr(4);
       }
    }
    //Adjustment for short years entered
    if (strYear.length == 2) {
    strYear = '20' + strYear;
    }
    strTemp = strDay;
    strDay = strMonth;
    strMonth = strTemp;
    intday = parseInt(strDay, 10);
    if (isNaN(intday)) {
    err = 2;
    return false;
    }
    intMonth = parseInt(strMonth, 10);
    if (isNaN(intMonth)) {
    for (i = 0;i<12;i++) {
    if (strMonth.toUpperCase() == strMonthArray[i].toUpperCase()) {
    intMonth = i+1;
    strMonth = strMonthArray[i];
    i = 12;
       }
    }
    if (isNaN(intMonth)) {
    err = 3;
    return false;
       }
    }
    intYear = parseInt(strYear, 10);
    if (isNaN(intYear)) {
    err = 4;
    return false;
    }
    if (intMonth>12 || intMonth<1) {
    err = 5;
    return false;
    }
    if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intday > 31 || intday < 1)) {
    err = 6;
    return false;
    }
    if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intday > 30 || intday < 1)) {
    err = 7;
    return false;
    }
    if (intMonth == 2) {
    if (intday < 1) {
    err = 8;
    return false;
    }
    if (LeapYear(intYear) == true) {
    if (intday > 29) {
    err = 9;
    return false;
       }
    }
    else {
    if (intday > 28) {
    err = 10;
    return false;
          }
       }
    }
    return true;
    }
    function LeapYear(intYear) {
    if (intYear % 100 == 0) {
    if (intYear % 400 == 0) { return true; }
    }
    else {
    if ((intYear % 4) == 0) { return true; }
    }
    return false;
    }
    //  End -->
    
    function checkInt(objName) {
      var numfield = objName;
      if (chkInt(objName.value) == false) {
        numfield.select();
        alert("Insira apenas caracteres numéricos. Por favor, tente novamente.")
        numfield.focus();
        return false;
      }
      else {
    	  return true;
      }
    }
    
    function checkFloat(objName) {
      var numfield = objName;
      if (chkFloat(objName.value) == false) {
        numfield.select();
        alert("Valor inválido.\nFavor tentar novamente.")
        numfield.focus();
        return false;
      }
      else {
        return true;
      }
    }
		
    function isFloat(val) {

      if (chkFloat(val) == false) {
        numfield.select();
        alert("Valor inválido.\nFavor tentar novamente.")
        numfield.focus();
        return false;
      }
      else {
        return true;
      }
    }
				
    function chkInt(num)
    {
      var parsednum;
      var pat;
      var res = new Array();
      pat = /(\.)/g;
      res = num.match(pat);
      if(res!=null)
      if(res.length>0)  return false;
      pat=/(\D)/g;
      res=num.match(pat);
      if(res!=null)
      if(res.length>1)
      return false;
      else //If Length is one
      if(res[0]=='-')
      {
      parsednum=parseInt(num);
      if(parsednum==num)
      return true;
      else
      return false;
      }
      else
      return false;
      else
      return true;
      }
      function chkFloat(num)
      {
      var parsednum;
      var pat;
      var res = new Array();
      pat = /(\.)/g;
      res = num.match(pat);
      if(res!=null)
      if(res.length>1)  
    	   return false;
      pat=/(\D)/g;
      res=num.match(pat);
      if(res!=null)
      if(res.length>2)  
    	   return false;
      else
         if(res.length==1)
    		 
      if(res[0]==',' || res[0]=='.')
         return true;
      else
         return false;
      else //res.length is 2
         if(res[0]==',' && res[1]=='.')
         {
           parsednum=parseFloat(num);
           if(parsednum==num)
              return true;
           else
              return false;
           }
         else
           return false;
      else
         return true;
    }
    
    function currency( num ) 
    { 
       var prefix = "R$"; 
       var suffix = ""; 
       if ( num < 0 ) 
       { 
           prefix = "(R$"; 
           suffix = ")"; 
           num = - num; 
       } 
           var temp = Math.round( num * 100.0 ); // convert to pennies! 
           if ( temp < 10 ) return prefix + "0,0" + temp + suffix; 
           if ( temp < 100 ) return prefix + "0," + temp + suffix; 
           temp = prefix + temp; // convert to string! 
           return temp.substring(0,temp.length-2) + "," + temp.substring(temp.length-2) + suffix; 
    }
    
    function currencyFormat(fld, milSep, decSep, e) {
        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 == 13) return true;  // Enter
        	  key = String.fromCharCode(whichCode);  // Get key value from key code
        if (strCheck.indexOf(key) == -1) return false;  // Not a valid key
        	  len = fld.value.length;
        for(i = 0; i < len; i++)
        if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;
        aux = '';
        for(; i < len; i++)
        if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);
        aux += key;
        len = aux.length;
        if (len == 0) fld.value = '';
        if (len == 1) fld.value = '0'+ decSep + '0' + aux;
        if (len == 2) fld.value = '0'+ decSep + aux;
        if (len > 2) {
        aux2 = '';
        for (j = 0, i = len - 3; i >= 0; i--) {
        if (j == 3) {
        aux2 += milSep;
        j = 0;
        }
        aux2 += aux.charAt(i);
        j++;
        }
        fld.value = '';
        len2 = aux2.length;
        for (i = len2 - 1; i >= 0; i--)
        fld.value += aux2.charAt(i);
        fld.value += decSep + aux.substr(len - 2, len);
        }
        return false;
    }
    
    /*
    This is one of the coolest features of qForms--the ease in which you can add
    your own validation methods. I think you'll be amazed at how simple it
    actually is. Here's the basic steps:
    
    1) Create a function to perform your validation logic.
    2) Use the "this.value" property (which is a special property for validation methods) if you want the value
    of the current form field.
    3) If you want to generate an error, simply declare a value for the this.error property.
    4) Register the function w/the _addValidator() function.
    
    So, here's what you'd do in your case:
    */
    function isCurrency(obj){
      var re = /\d{1,3}(.\d{3})*\,\d{2}$/;
      var isMatch = re.exec(obj.value);
      return isMatch;
    }
    
    
    var leapdays = new Array(31,29,31, 30,31,30, 31,31,30, 31,30,31); 
    var yeardays = new Array(31,28,31, 30,31,30, 31,31,30, 31,30,31); 
    
    function isLeapYear( year ){
      // is it leap year ? returns a boolean
      return ( (0 == (year%4)) && ( (0 != (year%100)) || (0 == (year%400)))); 
      // ie, if the year divides by 4, but not by 100 except when it divides by
      // 400, it is leap year
    } 
    
    function canonicalDate(day, month, year) 
    { 
      // return the number of days since the Jan 0 2000 (ie, 1/1/2K returns 1, 31/12/1999 returns 0) 
      // for days before Jan 1 2000, returns negative numbers
      var canonDate = 0;
      // if the function had no arguments, use today's date; 
    	var myDate = new Date();
      var mday = myDate.getDate(); 
      var mmon = myDate.getMonth(); 
      var myr  = myDate.getFullYear(); 
      if( arguments.length > 0 ) 	 { mday = arguments[0];	 } 
      if( arguments.length > 1 ) 	 { mmon = arguments[1];	 } 
      if( arguments.length > 2 ) 	 { myr  = arguments[2];	 } 
     if(myr >= 2000) 
    	{ canonDate += mday; 
    	  while(mmon > 0)  { canonDate += isLeapYear(myr) ? leapdays[mmon]: yeardays[mmon]; mmon--;} 
    	  while(myr > 2000){ canonDate += isLeapYear(myr) ? 366: 365; myr--;  } 
    	} 
     else
    	{ canonDate -= isLeapYear(myr) ? leapdays[mmon] - mday: yeardays[mmon] - mday; 
    	  while(mmon < 11)  { mmon++; canonDate -= isLeapYear(myr) ? leapdays[mmon]: yeardays[mmon];} 
    	  while(myr < 1999){ myr++; canonDate -= isLeapYear(myr) ? 366: 365;} 
    	} 
     return canonDate; 
    } 
    
      function dateDiff(date1,date2,diffopt) {
        
        var diff = date1 - date2;
        msPerDay = 24 * 60 * 60 * 1000 // Numéro de millisegundos por dia
        res = parseFloat ((diff) / msPerDay)   // ( Diferença em dias )

        switch (diffopt){
          case 'y':
             	res = parseInt(res/360);
        			break;   					  
          case 'm':
             	res = parseInt(res/30);
        			break;												
          case 'd':				
							res = parseInt(res);				 					    
        			break;														
        	case 'h':
             	res = parseInt(res*24);						
        			break;				
        }          
            
        return res;
    }
    					 
    function localDate(val) {
    	var datex;			 
    	if (val!='') {
    	 	  var dt = val.split('/');					 
    	 		var	d = dt[0];
    			var m = dt[1]-1;
    			var y = dt[2];
    			
    			datex = new Date(y,m,d);
    			return datex;
    	}
    	return null;						   
    };
    
    function disableForms (doc)	{
    										 
    	 for (var i=0;i<document.forms.length;i++){
         var f = document.forms[i];
    		   for (var j=0;j<f.elements.length;j++){
      		    var el = f.elements[j];
    
        			if (el.type=='text') { el.readOnly = true; } else { el.disabled = true; }								     		  
        			if (el.name.toUpperCase()=='EXIT') el.disabled = false;	
    					
    			 }					
    	 }				
    	 	 
    }	