// FormChek.js
//
// BASIC DATA VALIDATION FUNCTIONS:
//
// spaceOk -> True permite espacos
// eok     -> True permite empty
//
// isWhitespace (s)                    Check whether string s is empty or whitespace.
// isLetter (c,spaceOK)                Check whether character c is an Brazilian letter 
// isLetterEng (c,spaceOK)             Check whether character c is an English letter 
// isDigit (c)                         Check whether character c is a digit 
// isLetterOrDigit (c,spaceOK)         Check whether character c is a letter or digit.
// isInteger (s [,eok])                True if all characters in string s are numbers.
// isAlphabetic (s,spaceOK [,eok])     True if string s is Brazilian letters 
// isAlphanumeric (s,spaceOK [,eok])   True if string s is Brazilian letters and numbers only.
// isAlphabeticEng (s,spaceOK [,eok])  True if string s is English letters 
// isAlphanumericEng (s,spaceOK [,eok])True if string s is English letters and numbers only.
// charInString (c, s)                 True if character c is contained within string s.
// isIntegerInRange (s, a, b [,eok])   True if string s is an integer between a and b, inclusive.
// 
// isEmail (s [,eok])                  True if string s is a valid email address.
// isValidDate (sDate)                 True if string date form is a valid date (dd/mm/yyyy)
// isYear (s [,eok])                   True if string s is a valid Year number.
// isMonth (s [,eok])                  True if string s is a valid month between 1 and 12.
// isDay (s [,eok])                    True if string s is a valid day between 1 and 31.
// daysInFebruary (year)               Returns number of days in February of that year.
// isDate (year, month, day)           True if string arguments form a valid date.
// ValidaCPF(valor)		               True se for um CPF valido. Valor sem formatacao
// ValidaCGC(cgc)                      True se for um CGC válido. Valor sem formatação
// CheckCardNumber (form)

//
// FUNCTIONS TO REFORMAT DATA:
//
// stripCharsInBag (s, bag)            Removes all characters in string bag from string s.
// stripCharsNotInBag (s, bag)         Removes all characters NOT in string bag from string s.
// stripWhitespace (s)                 Removes all whitespace characters from s.
// stripInitialWhitespace (s)          Removes initial (leading) whitespace characters from s.

// VARIABLE DECLARATIONS

var digits = "0123456789";
var lowercaseLetters = "abcdefghijklmnopqrstuvwxyzáàâãéêíóòôõúç"
var uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZÁÀÃÂÉÊÍÌÓÒÔÕÚÇ"
var lowercaseLettersEng = "abcdefghijklmnopqrstuvwxyz"
var uppercaseLettersEng = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

// whitespace characters
var whitespace = " \t\n\r";

// Global variable defaultEmptyOK defines default return value 
// for many functions when they are passed the empty string. 
// By default, they will return defaultEmptyOK. 
// defaultEmptyOK is false
var defaultEmptyOK = false

function makeArray(n) {
//*** BUG: If I put this line in, I get two error messages:
//(1) Window.length can't be set by assignment
//(2) daysInMonth has no property indexed by 4
//If I leave it out, the code works fine.
//   this.length = n;
   for (var i = 1; i <= n; i++) {
      this[i] = 0
   } 
   return this
}

var daysInMonth = makeArray(12);
daysInMonth[1] = 31;
daysInMonth[2] = 29;   // must programmatically check this
daysInMonth[3] = 31;
daysInMonth[4] = 30;
daysInMonth[5] = 31;
daysInMonth[6] = 30;
daysInMonth[7] = 31;
daysInMonth[8] = 31;
daysInMonth[9] = 30;
daysInMonth[10] = 31;
daysInMonth[11] = 30;
daysInMonth[12] = 31;

// Check whether string s is empty.
function isEmpty(s)
{   return ((s == null) || (s.length == 0))
}

// Returns true if string s is empty or 
// whitespace characters only.
function isWhitespace (s)
{   var i;
    // Is s empty?
    if (isEmpty(s)) return true;

    // Search through string's characters one by one
    // until we find a non-whitespace character.
    // When we do, return false; if we don't, return true.
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (whitespace.indexOf(c) == -1) return false;
    }
    // All characters are whitespace.
    return true;
}

// Removes all characters which appear in string bag from string s.
function stripCharsInBag (s, bag)
{   var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

// Removes all characters which do NOT appear in string bag 
// from string s.
function stripCharsNotInBag (s, bag)
{   var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is in bag, append to returnString.
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) != -1) returnString += c;
    }
    return returnString;
}

// Removes all whitespace characters from s.
// Global variable whitespace (see above)
// defines which characters are considered whitespace.
function stripWhitespace (s)
{   return stripCharsInBag (s, whitespace)
}

// Returns true if single character c (actually a string)
// is contained within string s.
function charInString (c, s)
{   for (i = 0; i < s.length; i++)
    {   if (s.charAt(i) == c) return true;
    }
    return false
}

// Removes initial (leading) whitespace characters from s.
// Global variable whitespace (see above)
// defines which characters are considered whitespace.

function stripInitialWhitespace (s)
{   var i = 0;
    while ((i < s.length) && charInString (s.charAt(i), whitespace))
       i++;
    return s.substring (i, s.length);
}

// Returns true if character c is an English letter 
// (A .. Z, a..z).
//
// NOTE: Need i18n version to support European characters.
// This could be tricky due to different character
// sets and orderings for various languages and platforms.
//function isLetter (c)
//{   return ( ((c >= "a") && (c <= "z")) || ((c >= "A") && (c <= "Z")) )
//}
function isLetter (c)
{   
	if (isLetter.arguments.length == 1){
        return ( (charInString(c,lowercaseLetters)) || (charInString(c,uppercaseLetters)) )
    }
    else {
        return ( (charInString(c,lowercaseLetters)) || (charInString(c,uppercaseLetters)) || (charInString(c,whitespace)) )
    }
}

// Returns true if character c is a digit 
// (0 .. 9).
function isDigit (c)
{   return ((c >= "0") && (c <= "9"))
}

// Returns true if character c is a letter or digit.
function isLetterOrDigit (c)
{   
	if (isLetter.arguments.length == 1){
       return (isLetter(c) || isDigit(c))
    }
    else {
       return (isLetter(c,true) || isDigit(c))
    }
}

// isInteger (STRING s [, BOOLEAN emptyOK])
// 
// Returns true if all characters in string s are numbers.
//
// Accepts non-signed integers only. Does not accept floating 
// point, exponential notation, etc.
//
// We don't use parseInt because that would accept a string
// with trailing non-numeric characters.
//
// By default, returns defaultEmptyOK if s is empty.
// There is an optional second argument called emptyOK.
// emptyOK is used to override for a single function call
//      the default behavior which is specified globally by
//      defaultEmptyOK.
// If emptyOK is false (or any value other than true), 
//      the function will return false if s is empty.
// If emptyOK is true, the function will return true if s is empty.
//
// EXAMPLE FUNCTION CALL:     RESULT:
// isInteger ("5")            true 
// isInteger ("")             defaultEmptyOK
// isInteger ("-5")           false
// isInteger ("", true)       true
// isInteger ("", false)      false
// isInteger ("5", false)     true
function isInteger (s)
{   var i;
    if (isEmpty(s)) 
       if (isInteger.arguments.length == 1) return defaultEmptyOK;
       else return (isInteger.arguments[1] == true);

    // Search through string's characters one by one
    // until we find a non-numeric character.
    // When we do, return false; if we don't, return true.
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);
        if (!isDigit(c)) return false;
    }
    // All characters are numbers.
    return true;
}

// isAlphabetic (STRING s, BOOLEAN spaceOK [, BOOLEAN emptyOK])
// 
// Returns true if string s is English letters 
// (A .. Z, a..z) only.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.
//
// NOTE: Need i18n version to support European characters.
// This could be tricky due to different character
// sets and orderings for various languages and platforms.
function isAlphabetic (s, spaceOK)
{   var i;
    if (isEmpty(s)) 
       if (isAlphabetic.arguments.length == 2) return defaultEmptyOK;
       else return (isAlphabetic.arguments[2] == true);

    // Search through string's characters one by one
    // until we find a non-alphabetic character.
    // When we do, return false; if we don't, return true.
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is letter.
        var c = s.charAt(i);
        if (spaceOK) {
           if (!isLetter(c,true)) {
              return false;
           }
        } else {
           if (!isLetter(c)) {
              return false;
           }
        }
    }
    // All characters are letters.
    return true;
}

// isAlphanumeric (STRING s, BOOLEAN spaceOK [, BOOLEAN emptyOK])
// 
// Returns true if string s is English letters 
// (A .. Z, a..z) and numbers only.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.
//
// NOTE: Need i18n version to support European characters.
// This could be tricky due to different character
// sets and orderings for various languages and platforms.

function isAlphanumeric (s,spaceOK)
{   var i;
    if (isEmpty(s)) 
       if (isAlphanumeric.arguments.length == 2) return defaultEmptyOK;
       else return (isAlphanumeric.arguments[2] == true);

    // Search through string's characters one by one
    // until we find a non-alphanumeric character.
    // When we do, return false; if we don't, return true.
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number or letter.
        var c = s.charAt(i);

        if (spaceOK) {
           if (!(isLetter(c,true) || isDigit(c))) {
              return false;
           }
        } else {
           if (!(isLetter(c) || idDigit(c))) {
              return false;
           }
        }
    }

    // All characters are numbers or letters.
    return true;
}

// Returns true if character c is an English letter 
// (A .. Z, a..z).
//
// NOTE: Need i18n version to support European characters.
// This could be tricky due to different character
// sets and orderings for various languages and platforms.
//function isLetter (c)
//{   return ( ((c >= "a") && (c <= "z")) || ((c >= "A") && (c <= "Z")) )
//}
function isLetterEng (c)
{   
	if (isLetterEng.arguments.length == 1){
        return ( (charInString(c,lowercaseLettersEng)) || (charInString(c,uppercaseLettersEng)) )
    }
    else {
        return ( (charInString(c,lowercaseLettersEng)) || (charInString(c,uppercaseLettersEng)) || (charInString(c,whitespace)) )
    }
}

// isAlphabeticEng (STRING s, BOOLEAN spaceOK [, BOOLEAN emptyOK])
// 
// Returns true if string s is English letters 
// (A .. Z, a..z) only.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.
//
// NOTE: Need i18n version to support European characters.
// This could be tricky due to different character
// sets and orderings for various languages and platforms.
function isAlphabeticEng (s, spaceOK)
{   var i;
    if (isEmpty(s)) 
       if (isAlphabeticEng.arguments.length == 2) return defaultEmptyOK;
       else return (isAlphabeticEng.arguments[2] == true);

    // Search through string's characters one by one
    // until we find a non-alphabetic character.
    // When we do, return false; if we don't, return true.
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is letter.
        var c = s.charAt(i);
        if (spaceOK) {
           if (!isLetterEng(c,true)) {
              return false;
           }
        } else {
           if (!isLetterEng(c)) {
              return false;
           }
        }
    }
    // All characters are letters.
    return true;
}

// isAlphanumericEng (STRING s, BOOLEAN spaceOK [, BOOLEAN emptyOK])
// 
// Returns true if string s is English letters 
// (A .. Z, a..z) and numbers only.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.
//
// NOTE: Need i18n version to support European characters.
// This could be tricky due to different character
// sets and orderings for various languages and platforms.

function isAlphanumericEng (s,spaceOK)
{   var i;
    if (isEmpty(s)) 
       if (isAlphanumericEng.arguments.length == 2) return defaultEmptyOK;
       else return (isAlphanumericEng.arguments[2] == true);

    // Search through string's characters one by one
    // until we find a non-alphanumeric character.
    // When we do, return false; if we don't, return true.
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number or letter.
        var c = s.charAt(i);

        if (spaceOK) {
           if (!(isLetterEng(c,true) || isDigit(c))) {
              return false;
           }
        } else {
           if (!(isLetterEng(c) || idDigit(c))) {
              return false;
           }
        }
    }

    // All characters are numbers or letters.
    return true;
}

// isEmail (STRING s [, BOOLEAN emptyOK])
// 
// Email address must be of form a@b.c -- in other words:
// * there must be at least one character before the @
// * there must be at least one character before and after the .
// * the characters @ and . are both required
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.
function isEmail (s)
{   if (isEmpty(s)) 
       if (isEmail.arguments.length == 1) return defaultEmptyOK;
       else return (isEmail.arguments[1] == true);
   
    // is s whitespace?
    if (isWhitespace(s)) return false;
    
   // Begin
    
    var checkTLD=1;

/* The following is the list of known TLDs that an e-mail address must end with. */

var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;

/* The following pattern is used to check if the entered e-mail address
fits the user@domain format.  It also is used to separate the username
from the domain. */

var emailPat=/^(.+)@(.+)$/;

/* The following string represents the pattern for matching all special
characters.  We don't want to allow special characters in the address. 
These characters include ( ) < > @ , ; : \ " . [ ] */

var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";

/* The following string represents the range of characters allowed in a 
username or domainname.  It really states which chars aren't allowed.*/

var validChars="\[^\\s" + specialChars + "\]";

/* The following pattern applies if the "user" is a quoted string (in
which case, there are no rules about which characters are allowed
and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
is a legal e-mail address. */

var quotedUser="(\"[^\"]*\")";

/* The following pattern applies 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@somewhere.com, john and doe are words.
Basically, a word is either an atom or quoted string. */

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=s.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. */

return false;
}
var user=matchArray[1];
var domain=matchArray[2];

// Start by checking that only basic ASCII characters are in the strings (0-127).

for (i=0; i<user.length; i++) {
if (user.charCodeAt(i)>127) {
return false;
   }
}
for (i=0; i<domain.length; i++) {
if (domain.charCodeAt(i)>127) {
return false;
   }
}

// See if "user" is valid 

if (user.match(userPat)==null) {

// user is not valid

return false;
}

/* if the e-mail address is at an IP address (as opposed to a symbolic
host name) 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) {
return false;
   }
}
return true;
}

// Domain is symbolic name.  Check if it's valid.
 
var atomPat=new RegExp("^" + atom + "$");
var domArr=domain.split(".");
var len=domArr.length;
for (i=0;i<len;i++) {
if (domArr[i].search(atomPat)==-1) {
return false;
   }
}

/* domain name seems valid, but now make sure that it ends in a
known top-level domain (like com, edu, gov) or a two-letter word,
representing country (uk, nl), and that there's a hostname preceding 
the domain or country. */

if (checkTLD && domArr[domArr.length-1].length!=2 && 
domArr[domArr.length-1].search(knownDomsPat)==-1) {
return false;
}

// Make sure there's a host name preceding the domain.

if (len<2) {
return false;
}

// If we've gotten this far, everything's valid!
return true;

    
}

function isIntegerInRange (s, a, b)
{   if (isEmpty(s)) 
       if (isIntegerInRange.arguments.length == 1) return defaultEmptyOK;
       else return (isIntegerInRange.arguments[1] == true);

    // Catch non-integer strings to avoid creating a NaN below,
    // which isn't available on JavaScript 1.0 for Windows.
    if (!isInteger(s, false)) return false;

    // Now, explicitly change the type to integer via parseInt
    // so that the comparison code below will work both on 
    // JavaScript 1.2 (which typechecks in equality comparisons)
    // and JavaScript 1.1 and before (which doesn't).
    var num = parseInt (s,10);
    return ((num >= a) && (num <= b));
}

// isYear (STRING s [, BOOLEAN emptyOK])
// 
// isYear returns true if string s is a valid 
// Year number.  Must be 4 digits only.
// 
// For Year 2000 compliance, you are advised
// to use 4-digit year numbers everywhere.
function isYear (s)
{   if (isEmpty(s)) 
       if (isYear.arguments.length == 1) return defaultEmptyOK;
       else return (isYear.arguments[1] == true);
    return ((s.length == 4));
}

// isMonth (STRING s [, BOOLEAN emptyOK])
// 
// isMonth returns true if string s is a valid 
// month number between 1 and 12.
function isMonth (s)
{   if (isEmpty(s)) 
       if (isMonth.arguments.length == 1) return defaultEmptyOK;
       else return (isMonth.arguments[1] == true);
    return isIntegerInRange (s, 1, 12);
}

// isDay (STRING s [, BOOLEAN emptyOK])
// 
// isDay returns true if string s is a valid 
// day number between 1 and 31.
// 
// For explanation of optional argument emptyOK,
// see comments of function isInteger.
function isDay (s)
{   if (isEmpty(s)) 
       if (isDay.arguments.length == 1) return defaultEmptyOK;
       else return (isDay.arguments[1] == true);   
    return isIntegerInRange (s, 1, 31);
}

// daysInFebruary (INTEGER year)
// 
// Given integer argument year,
// returns number of days in February of that year.
function daysInFebruary (year)
{   // February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (  ((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0) ) ) ? 29 : 28 );
}

// isDate (STRING year, STRING month, STRING day)
//
// isDate returns true if string arguments year, month, and day 
// form a valid date.
// 
function isDate (year, month, day)
{   // catch invalid years (not 2- or 4-digit) and invalid months and days.
    if (! (isYear(year, false) && isMonth(month, false) && isDay(day, false))) return false;

    // Explicitly change type to integer to make code work in both
    // JavaScript 1.1 and JavaScript 1.2.
    var intYear = parseInt(year,10);
    var intMonth = parseInt(month,10);
    var intDay = parseInt(day,10);

    // catch invalid days, except for February
    if (intDay > daysInMonth[intMonth]) return false; 
    if ((intMonth == 2) && (intDay > daysInFebruary(intYear))) return false;
    return true;
}
// isValidDate (STRING sDate)
//
// isValidDate returns true if string date form is a valid date.
// Format: dd/mm/yyyy
// 
function isValidDate (sDate){
  day = sDate.substr(0,2);
  month = sDate.substr(3,2);
  year = sDate.substr(6);
  
  if (!(year.length == 4) || !(isInteger(year))) {
     return false;
  }
  return (isDate(year,month,day));
}

// ValidaCPF(valor)
//
// Returna True se o valor for um CPF Valido. Utilizar apenas numeros, sem formatacao
// 
function ValidaCPF(valor) {
	if (valor == "00000000000" || valor == "11111111111" || valor == "22222222222" || valor == "33333333333" || valor == "44444444444" || valor == "55555555555" || valor == "66666666666" || valor == "77777777777" || valor == "88888888888" || valor == "99999999999"){
		return (false);
	}
	givenValue = valor.substring(0,9);
	calculatedDv1 = getDvCpf(givenValue);
	calculatedDv2 = getDvCpf(givenValue + calculatedDv1);
	calculatedDv = "" + calculatedDv1 + calculatedDv2;
	
	if (calculatedDv == valor.substring(9))
		return (true);
	else
		return (false);
}

// Subfuncao de validacao de CPF. Calcula Digito Verificador em modulo 11
function getDvCpf(valor){
	soma = 0;
	fator = 2;
	i = 0;
	for (i=valor.length-1;i>=0;i--){
		soma = soma + (parseInt(valor.charAt(i),10) * fator);
		fator ++;
	}
	soma = 11 - (soma % 11);
	if (soma >= 10)
		soma = 0;
   	return (soma);
}

function CheckReserva(form)
{
	if (form.qtd_pessoas.value.length == 0)
	{
		alert('Você deve preencher o campo quantidade de pessoas.')
		form.qtd_pessoas.focus();
		return false;
	}
	
	if(!(isInteger(form.qtd_pessoas.value)))
	{
		alert('O campo quantidade de pessoas deve conter apenas caracteres numéricos.')
		form.qtd_pessoas.focus();
		form.qtd_pessoas.select();
		return false;
	}
	
	if (form.qtd_pessoas.value <= 0)
	{
		alert('A quantidade de pessoas deve ser maior do que 0.')
		form.qtd_pessoas.focus();
		form.qtd_pessoas.select();
		return false;
	}
	
	if (form.data.value.length == 0)
	{
		alert('Você deve preencher o campo data.')
		form.data.focus();
		return false;
	}
	
	if(!(isValidDate(form.data.value)))
	{
		alert('Você deve prrencher o campo data no formato dd/mm/aaaa')
		form.data.focus();
		form.data.select();
		return false;
	}
	
	else
	{
		form.submit();
	}
}

//Valida CGC

function ValChar(ch) {
	if (ch=="0") return 0
	else if (ch=="1") return 1
	else if (ch=="2") return 2
	else if (ch=="3") return 3
	else if (ch=="4") return 4
	else if (ch=="5") return 5
	else if (ch=="6") return 6
	else if (ch=="7") return 7
	else if (ch=="8") return 8
	else if (ch=="9") return 9
	else return 10
}

//Verifica se o argumento é um CGC válido de 8 dígitos
function ChecaCGC8 (CKCGC) {
var CGC = CKCGC;
var NewCGC = "";
//Elimina todos os espaços, pontos, barras e traços do CGC
for (i=0;i<CGC.length;i++) { //>
	if (CGC.charAt(i) != " " && CGC.charAt(i) != "." && CGC.charAt(i) != "/" && CGC.charAt(i) != "-") NewCGC = NewCGC + CGC.charAt(i);
}
//Verifica tamanho do CGC
if (NewCGC.length!=8) {
	return false;
}
//verifica se todos os caracteres são numéricos
var Numerico = false;
var Numeros = "0123456789";
for (i=0;i<NewCGC.length;i++) { //>
	Numerico = false;
	for (j=0;j<Numeros.length;j++) { //>
		if (NewCGC.charAt(i) == Numeros.charAt(j)) {
			Numerico = true;
			break;
		}
	}
	if (!Numerico) {
		return false;
	}
}
//Calcula os dígitos verificadores
var s1 = 0;
aux = 0;
soma = 0
for (i=1;i<=8;i++) {
	//alert("i="+i+" - char(i-1)="+NewCGC.charAt(i-1));
	aux = (ValChar(NewCGC.charAt(i-1)))*((i % 2)+1);
	//alert ("aux="+aux);
	if (aux>9) aux = aux-9;
	//alert ("aux="+aux);
	soma = soma + aux;
}
r1 = soma % 10;
//alert("soma="+soma+" - resto="+r1);
if (r1==0) return (true)
else {
	return (false);
}
}

//Verifica se o argumento é um CGC válido
function ChecaCGC (CKCGC) {
var CGC = CKCGC;
var NewCGC = "";
//Verifica tamanho do CGC
if (CGC.length!=14) {
	return false;
}
//Calcula os dígitos verificadores
//Guarda os 12 primeiros digitos
var DVCGC = CGC.substring(0,12);
//calcula o primeiro digito verificador
var s1 = 0;
for (i=1;i<=4;i++) s1 = s1 + (ValChar(DVCGC.charAt(i-1))*(6-i));
for (i=5;i<=12;i++) s1 = s1 + (ValChar(DVCGC.charAt(i-1))*(14-i));
r1 = s1 % 11;
if (r1<2) dv1=0;
else dv1 = 11 - r1;
//calcula o segundo digito verificador
var s2 = dv1*2;
for (i=1;i<=5;i++) s2 = s2 + (ValChar(DVCGC.charAt(i-1))*(7-i));
for (i=6;i<=12;i++) s2 = s2 + (ValChar(DVCGC.charAt(i-1))*(15-i));
r2 = s2 % 11;
if (r2<2) dv2=0;
else dv2 = 11 - r2;
//junta os digitos verificadores
var DV = "";
DV = DV + dv1 + dv2;
//guarda os digitos verificadores do CGC digitado (últimas duas posições no string)
var NewDV = CGC.substring(12,14)
if (NewDV==DV) { //se o DV calculado for igual ao digitado, retorna true
	return true
}
else {
	return false
}
}

function ValidaCGC(theField) {



	if(theField.value.length>0){


	var a = theField.value;
	var b = "";
	var c = "";
	var d = 0;
	for(cont=0;cont<a.length;cont++)
	{
		if(	a.charAt(cont)=="0" || a.charAt(cont)=="1" || a.charAt(cont)=="2" || a.charAt(cont)=="3" || a.charAt(cont)=="4" || a.charAt(cont)=="5" || a.charAt(cont)=="6" || a.charAt(cont)=="7" || a.charAt(cont)=="8" || a.charAt(cont)=="9"){
			b = b + a.charAt(cont);
		}
	}
	a = b;

	//if(a==false){
	//		alert("CGC Inválido");
	//		return (false);
	//}

	//SE NÃO FOR IDENTIFICADO NENHUM NÚMERO - "CPF Inválido"
	if(a.length==""){
		//alert("CGC Inválido");
		theField.select()
		return (false);
	}


	if (a!="") { //se o campo CGC tiver algum valor, verifica
		//if (a.length > 14)  //verifica se o tamanho não é maior que 14
		//{
		//	alert("O campo \""+theField.name+"\" deve ter no máximo 14 dígitos.");
			//theField.focus();
		//	return (false);
		//}
		// verifica se todos os caracteres digitados são numeros
		var checkOK = "0123456789-";
		var checkStr = a;
		var allValid = true;
		var decPoints = 0;
		var allNum = "";
		for (i = 0;  i < checkStr.length;  i++)
		{
			ch = checkStr.charAt(i);
			for (j = 0;  j < checkOK.length;  j++)
			if (ch == checkOK.charAt(j)) break;
			if (j == checkOK.length)
			{
				allValid = false;
				break;
			}
			allNum += ch;
		}
		if (!allValid)
		{
			alert("O campo \""+theField.name+"\" deve conter apenas números.");
			theField.select();
			return (false);
		}
		//checa se o campo é CGC válido, retorna true e envia o formulário
		if (ChecaCGC(a)||ChecaCGC8(a)){

		//************************************************************************
			//FORMATAÇÃO DO CGC NA NOVA MASKARA
			b = "99.999999/9999-99";		// MASCARA QUE VAI SER APLICADA NO CGC

			for(cont=0;cont<b.length;cont++)
			{
			  numero = b.charAt(cont);
				if(numero == "9")
				{

					if(a.charAt(cont-d)!=""){
						c= c + a.charAt(cont-d);
					}
					else
					{
						c= c + "0";
					}
				}
		    else
		    {
					c= c + b.charAt(cont);
					d = d + 1;
		    }
		    numero = "";
			}

			//document.ThisForm.cgc.value = c;
			
			theField.value = c;
			
		//************************************************************************
		//document.ThisForm.submit();
		return (true);
		
		}

		else
		{
			//alert(theField.name+" inválido!");
			theField.select();
			return (false);
		}
	}

}

}

//= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
//								Cartão de Crédito
//= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

var Cards = new makeArray(8);
Cards[0] = new CardType("MasterCard", "51,52,53,54,55", "16");
var MasterCard = Cards[0];
Cards[1] = new CardType("Visa", "4", "13,16");
var VisaCard = Cards[1];
Cards[2] = new CardType("AmExCard", "34,37", "15");
var AmExCard = Cards[2];
Cards[3] = new CardType("DinersClubCard", "30,36,38", "14");
var DinersClubCard = Cards[3];
Cards[4] = new CardType("DiscoverCard", "6011", "16");
var DiscoverCard = Cards[4];
Cards[5] = new CardType("enRouteCard", "2014,2149", "15");
var enRouteCard = Cards[5];
Cards[6] = new CardType("JCBCard", "3088,3096,3112,3158,3337,3528", "16");
var JCBCard = Cards[6];
var LuhnCheckSum = Cards[7] = new CardType();


/*************************************************************************\
Object CardType([String cardtype, String rules, String len, int year, 
                                        int month])
cardtype    : type of card, eg: MasterCard, Visa, etc.
rules       : rules of the cardnumber, eg: "4", "6011", "34,37".
len         : valid length of cardnumber, eg: "16,19", "13,16".
year        : year of expiry date.
month       : month of expiry date.
eg:
var VisaCard = new CardType("Visa", "4", "16");
var AmExCard = new CardType("AmEx", "34,37", "15");
\*************************************************************************/
function CardType() {
var n;
var argv = CardType.arguments;
var argc = CardType.arguments.length;

this.objname = "object CardType";

var tmpcardtype = (argc > 0) ? argv[0] : "CardObject";
var tmprules = (argc > 1) ? argv[1] : "0,1,2,3,4,5,6,7,8,9";
var tmplen = (argc > 2) ? argv[2] : "13,14,15,16,19";

this.setCardNumber = setCardNumber;  // set CardNumber method.
this.setCardType = setCardType;  // setCardType method.
this.setLen = setLen;  // setLen method.
this.setRules = setRules;  // setRules method.
this.setExpiryDate = setExpiryDate;  // setExpiryDate method.

this.setCardType(tmpcardtype);
this.setLen(tmplen);
this.setRules(tmprules);
if (argc > 4)
this.setExpiryDate(argv[3], argv[4]);

this.checkCardNumber = checkCardNumber;  // checkCardNumber method.
this.getExpiryDate = getExpiryDate;  // getExpiryDate method.
this.getCardType = getCardType;  // getCardType method.
this.isCardNumber = isCardNumber;  // isCardNumber method.
this.isExpiryDate = isExpiryDate;  // isExpiryDate method.
this.luhnCheck = luhnCheck;// luhnCheck method.
return this;
}

/*************************************************************************\
boolean checkCardNumber([String cardnumber, int year, int month])
return true if cardnumber pass the luhncheck and the expiry date is
valid, else return false.
\*************************************************************************/
function checkCardNumber() {
var argv = checkCardNumber.arguments;
var argc = checkCardNumber.arguments.length;
var cardnumber = (argc > 0) ? argv[0] : this.cardnumber;
var year = (argc > 1) ? argv[1] : this.year;
var month = (argc > 2) ? argv[2] : this.month;

this.setCardNumber(cardnumber);
this.setExpiryDate(year, month);

if (!this.isCardNumber())
return false;
if (!this.isExpiryDate())
return false;

return true;
}
/*************************************************************************\
String getCardType()
return the cardtype.
\*************************************************************************/
function getCardType() {
return this.cardtype;
}
/*************************************************************************\
String getExpiryDate()
return the expiry date.
\*************************************************************************/
function getExpiryDate() {
return this.month + "/" + this.year;
}
/*************************************************************************\
boolean isCardNumber([String cardnumber])
return true if cardnumber pass the luhncheck and the rules, else return
false.
\*************************************************************************/
function isCardNumber() {
var argv = isCardNumber.arguments;
var argc = isCardNumber.arguments.length;
var cardnumber = (argc > 0) ? argv[0] : this.cardnumber;
if (!this.luhnCheck())
return false;

for (var n = 0; n < this.len.size; n++)
if (cardnumber.toString().length == this.len[n]) {
for (var m = 0; m < this.rules.size; m++) {
var headdigit = cardnumber.substring(0, this.rules[m].toString().length);
if (headdigit == this.rules[m])
return true;
}
return false;
}
return false;
}

/*************************************************************************\
boolean isExpiryDate([int year, int month])
return true if the date is a valid expiry date,
else return false.
\*************************************************************************/
function isExpiryDate() {
var argv = isExpiryDate.arguments;
var argc = isExpiryDate.arguments.length;

year = argc > 0 ? argv[0] : this.year;
month = argc > 1 ? argv[1] : this.month;

if (!isNum(year+""))
return false;
if (!isNum(month+""))
return false;
today = new Date();
expiry = new Date(year, month);
if (today.getTime() > expiry.getTime())
return false;
else
return true;
}

/*************************************************************************\
boolean isNum(String argvalue)
return true if argvalue contains only numeric characters,
else return false.
\*************************************************************************/
function isNum(argvalue) {
argvalue = argvalue.toString();

if (argvalue.length == 0)
return false;

for (var n = 0; n < argvalue.length; n++)
if (argvalue.substring(n, n+1) < "0" || argvalue.substring(n, n+1) > "9")
return false;

return true;
}

/*************************************************************************\
boolean luhnCheck([String CardNumber])
return true if CardNumber pass the luhn check else return false.
Reference: http://www.ling.nwu.edu/~sburke/pub/luhn_lib.pl
\*************************************************************************/
function luhnCheck() {
var argv = luhnCheck.arguments;
var argc = luhnCheck.arguments.length;

var CardNumber = argc > 0 ? argv[0] : this.cardnumber;

if (! isNum(CardNumber)) {
return false;
  }

var no_digit = CardNumber.length;
var oddoeven = no_digit & 1;
var sum = 0;

for (var count = 0; count < no_digit; count++) {
var digit = parseInt(CardNumber.charAt(count));
if (!((count & 1) ^ oddoeven)) {
digit *= 2;
if (digit > 9)
digit -= 9;
}
sum += digit;
}
if (sum % 10 == 0)
return true;
else
return false;
}

/*************************************************************************\
ArrayObject makeArray(int size)
return the array object in the size specified.
\*************************************************************************/
function makeArray(size) {
this.size = size;
return this;
}

/*************************************************************************\
CardType setCardNumber(cardnumber)
return the CardType object.
\*************************************************************************/
function setCardNumber(cardnumber) {
this.cardnumber = cardnumber;
return this;
}

/*************************************************************************\
CardType setCardType(cardtype)
return the CardType object.
\*************************************************************************/
function setCardType(cardtype) {
this.cardtype = cardtype;
return this;
}

/*************************************************************************\
CardType setExpiryDate(year, month)
return the CardType object.
\*************************************************************************/
function setExpiryDate(year, month) {
this.year = year;
this.month = month;
return this;
}

/*************************************************************************\
CardType setLen(len)
return the CardType object.
\*************************************************************************/
function setLen(len) {
// Create the len array.
if (len.length == 0 || len == null)
len = "13,14,15,16,19";

var tmplen = len;
n = 1;
while (tmplen.indexOf(",") != -1) {
tmplen = tmplen.substring(tmplen.indexOf(",") + 1, tmplen.length);
n++;
}
this.len = new makeArray(n);
n = 0;
while (len.indexOf(",") != -1) {
var tmpstr = len.substring(0, len.indexOf(","));
this.len[n] = tmpstr;
len = len.substring(len.indexOf(",") + 1, len.length);
n++;
}
this.len[n] = len;
return this;
}

/*************************************************************************\
CardType setRules()
return the CardType object.
\*************************************************************************/
function setRules(rules) {
// Create the rules array.
if (rules.length == 0 || rules == null)
rules = "0,1,2,3,4,5,6,7,8,9";
  
var tmprules = rules;
n = 1;
while (tmprules.indexOf(",") != -1) {
tmprules = tmprules.substring(tmprules.indexOf(",") + 1, tmprules.length);
n++;
}
this.rules = new makeArray(n);
n = 0;
while (rules.indexOf(",") != -1) {
var tmpstr = rules.substring(0, rules.indexOf(","));
this.rules[n] = tmpstr;
rules = rules.substring(rules.indexOf(",") + 1, rules.length);
n++;
}
this.rules[n] = rules;
return this;
}

//= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
//								Cartão de Crédito
//= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =


function Redireciona(pagina)
{
	self.location=pagina
}