// DOM para o Opera pegar corretamente os elementos
isDOM = document.getElementById ? 1 : 0;

function validar(f)
{
    for (var i = 0; i < campos_obrigatorios.length; ++i)
    {
        // Pegamos o nome da funcao (posicao 1), e em seguida os parametros:
        // 1) formulario (f)
        // 2) campo a ser analisado (posicao 0)
        // 3) mensagem de erro (posicao 2)
        // 4) se o campo pode ser vazio ou nao (posicao 3)
        if (! campos_obrigatorios[i][1](f, campos_obrigatorios[i][0], campos_obrigatorios[i][2]) )
        {
            return false;
        }
    }
    return true;
}

//************************************************************************************************************************
// Remove todos os espacos em branco de uma string
//************************************************************************************************************************
function stripSpaces(x)
{
    while (x.substring(0,1) == ' ')
        x = x.substring(1);
    return x;
}

//************************************************************************************************************************
// Retorna 'true' se a variavel for vazia,
// ou 'false', caso contrario
//************************************************************************************************************************
function empty(x)
{
    if (x.length > 0)
        return false;
    else
        return true;
}

//************************************************************************************************************************
// Funcao para TEXT e TEXTAREA
// Verifica se o campo esta vazio ou nao
//************************************************************************************************************************
function verifica_brancos(formobj, field, msg)
{
    var e = formobj.elements[field];

    if (!empty(stripSpaces(e.value)))
        return true;

    alert(msg);
    e.focus();
    e.select();
    return false;
}

//************************************************************************************************************************
// Função para RADIO e CHECKBOX
// Verifica se o radio ou checkbox esta marcado ou nao
//************************************************************************************************************************
function verifica_marcados(formobj, field, msg)
{
    var e;
    var j = 0;  // qual elemento de RADIO/CHECKBOX a retornar

    // Para o Opera
    if (isDOM)
    {
        e = document.getElementsByTagName('INPUT');  // retorna uma lista encadeada
        // varrendo a lista
        for (var i = 0; i <= e.length-1; ++i)
        {
            if (e[i].name == field)
            {
                if (j == 0)
                    j = i;
                if (e[i].checked)
                    return true;
            }
        }
    }
    else
    {
        e = formobj.elements[field];    // retorna um array de elementos
        for (var i = 0; i < e.length; ++i)
        {
            if (e[i].checked)
            {
                return true;
                break;
            }
        }
    }

    alert(msg);
    e[j].focus();
    return false;
}

//************************************************************************************************************************
// Funcao para SELECT
// Verifica se determinado elemento de um campo 'select' esta selecionado ou nao
//************************************************************************************************************************
function verifica_selecionados(formobj, field, msg)
{
    var e = formobj.elements[field];

    if (e.selectedIndex == -1 || e.options[e.selectedIndex].value == 0)
    {
        alert(msg);
        e.focus();
        return false;
    }
    else
        return true;
/*    if (! e.selectedIndex == 0)
        return true;

    alert(msg);
    e.focus();
    return false;*/
}

//************************************************************************************************************************
// Verifica se os valores digitados em determinado campo sao apenas numericos
//************************************************************************************************************************
function verifica_numericos(formobj, field, msg)
{
    var e = formobj.elements[field];

    if ( !isNaN(parseInt(e.value)) )
        return true;

    alert(msg);
    e.focus();
    e.select();
    return false;
}

//************************************************************************************************************************
// Funcao para validar e-mail
//************************************************************************************************************************
function verifica_email(formobj, field, msg)
{
    var e = formobj.elements[field];

    if (e.value == null)
    {
        alert(msg);
        e.focus();
        return false;
    }

    // tirando os espaços vazios no endereco
    for (x = 1; x < e.value.length; x++)
    {
        e.value = e.value.replace(' ', '');
    }

    var emailStr = e.value;
    var emailPat = /^(.+)@(.+)$/;
    var specialChars = "\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
    var validChars = "\[^\\s" + specialChars + "\]";
    var quotedUser = "(\"[^\"]*\")";
    var ipDomainPat = /^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
    var atom = validChars + '+';
    var word = "(" + atom + "|" + quotedUser + ")";
    var userPat = new RegExp("^" + word + "(\\." + word + ")*$");
    var domainPat = new RegExp("^" + atom + "(\\." + atom +")*$");
    var matchArray = emailStr.match(emailPat);

    if (matchArray == null)
    {
        alert("O e-mail informado não é válido!");
        e.focus();
        e.select();
        return false;
    }

    var user = matchArray[1];
    var domain = matchArray[2];

    if (user.match(userPat) == null)
    {
        alert("Seu nome de usuário parece não ser válido!");
        e.focus();
        e.select();
        return false;
    }

    var IPArray = domain.match(ipDomainPat);

    if (IPArray != null)
    {
        for (var i = 1; i <= 4; i++)
        {
            if (IPArray[i] > 255)
            {
                alert("O endereço do IP parece não ser válido!");
                e.focus();
                e.select();
                return false;
            }
        }
        return true;
    }

    var domainArray = domain.match(domainPat);

    if (domainArray == null)
    {
        alert("O domínio parece não ser válido!");
        e.focus();
        e.select();
        return false;
    }

    var atomPat = new RegExp(atom, "g");
    var domArr = domain.match(atomPat);

    if (domArr[domArr.length-1].length < 2 || domArr[domArr.length-1].length > 3)
    {
        alert("O e-mail deve conter três letras de domínio,\nou pelo menos duas letras do país.");
        e.focus();
        e.select();
        return false;
    }

    if (domArr.length < 2)
    {
        alert("Não foi possível contatar o provedor!");
        e.focus();
        e.select();
        return false;
    }
    return true;
}

//********************************************************************************
// Funcao para validacao de datas
//********************************************************************************
function verifica_data(formobj, field, msg)
{
    if (empty(stripSpaces(formobj.elements[field].value)))
    {
        alert(msg);
        formobj.elements[field].focus();
        formobj.elements[field].select();
        return false;
    }
    else
    {
        var checkstr = "0123456789";
        var DateField = formobj.elements[field];
        var DateValue = "";
        var DateTemp = "";
        var seperator = "/";
        var day;
        var month;
        var year;
        var leap = 0;
        var err = 0;
        var msgerr = "";
        var i;

        err = 0;
        DateValue = DateField.value;

        // Deletando todos os caracteres, exceto os numeros
        for (i = 0; i < DateValue.length; i++)
        {
            if (checkstr.indexOf(DateValue.substr(i,1)) >= 0)
            {
                DateTemp = DateTemp + DateValue.substr(i,1);
            }
        }
        DateValue = DateTemp;

        if (empty(stripSpaces(DateValue)))
        {
            alert("A data deve conter apenas números!");
            DateField.focus();
            DateField.select();
            return false;
        }
        else
        {
            // Se o usuario digitar o ano com apenas dois
            // digitos, formatamos o campo automaticamente
            if (DateValue.length == 6)
            {
                DateValue = DateValue.substr(0,4) + '19' + DateValue.substr(4,2);
            }

            // Se o tamanho do campo for invalido (diferente de 8)
            if (DateValue.length != 8)
            {
                err = 19;
                msgerr = "Data maior que o permitido!";
            }

            // O ano nao pode ser zero
            year = DateValue.substr(4,4);
            if (year == 0)
            {
                err = 20;
                msgerr = "O ano não pode ser nulo!";
            }
            // O ano nao pode ser menor que 1900
            if (year < 1900)
            {
                err = 18;
                msgerr = "O ano não pode ser anterior à 1900!";
            }

            // O mes deve estar compreendido entre 1 e 12
            month = DateValue.substr(2,2);
            if ((month < 1) || (month > 12))
            {
                err = 21;
                msgerr = "O mês deve estar compreendido entre 1 e 12!";
            }

            // O dia nao pode ser menor que 1
            day = DateValue.substr(0,2);
            if (day < 1)
            {
                err = 22;
                msgerr = "O dia não pode ser menor que 1!";
            }

            // Verificando se o ano eh bissexto
            if ((year % 4 == 0) || (year % 100 == 0) || (year % 400 == 0))
            {
                leap = 1;
            }
            // Se o ano for bissexto, no mes de Fevereiro,
            // o dia nao pode ser maior que 29
            if ((month == 2) && (leap == 1) && (day > 29))
            {
                err = 23;
                msgerr = "Dia inexistente no mês de Fevereiro!";
            }
            // Ja se o ano nao for bissexto, no mes de Fevereiro,
            // o dia nao pode ser maior que 28
            if ((month == 2) && (leap != 1) && (day > 28))
            {
                err = 24;
                msgerr = "Dia inexistente no mês de Fevereiro!";
            }

            // Nos meses de Janeiro, Marco, Maio, Julho, Agosto,
            // Outubro e Dezembro, o dia nao pode ser maior que 31
            if ((day > 31) && ((month == "01") || (month == "03") || (month == "05") || (month == "07") || (month == "08") || (month == "10") || (month == "12")))
            {
                err = 25;
                msgerr = "O dia não pode ser maior que 31!";
            }

            // Ja nos meses de Abril, Junho, Setembro e Novembro,
            // o dia nao pode ser maior que 30
            if ((day > 30) && ((month == "04") || (month == "06") || (month == "09") || (month == "11")))
            {
                err = 26;
                msgerr = "Neste mês, o dia não pode ser maior que 30!";
            }

            // Se nao houve erros
            if ((day == 0) && (month == 0) && (year == 00))
            {
                err = 0;
                day = "";
                month = "";
                year = "";
                seperator = "";
            }

            // Quando nao ha erros, escrevemos a data
            // completa no campo correspondente
            if (err == 0)
            {
                DateField.value = day + seperator + month + seperator + year;
                return true;
            }
            /*** Tratamento dos Erros ***/
            else
            {
                if (msgerr != "")
                    alert("Data inválida!\n" + msgerr);
                else
                    alert("Data inválida!");
                DateField.focus();
                DateField.select();
                return false;
            }
        } // else
    } // else
}

//********************************************************************************
// Funcao para formatacao de campos 'text'
//********************************************************************************
function txtBoxFormat(objForm, strField, sMask, evtKeyPress)
{
    var i, nCount, sValue, fldLen, mskLen, bolMask, sCod, nTecla;

    if (document.all)   // Internet Explorer
    {
        nTecla = evtKeyPress.keyCode;
    }
    else if (document.layers)    // Nestcape
    {
        nTecla = evtKeyPress.which;
    }

    sValue = objForm[strField].value;

    // Limpa todos os caracteres de formatacao
    // que ja estiverem no campo
    sValue = sValue.toString().replace( "-", "" );
    sValue = sValue.toString().replace( "-", "" );
    sValue = sValue.toString().replace( ".", "" );
    sValue = sValue.toString().replace( ".", "" );
    sValue = sValue.toString().replace( "/", "" );
    sValue = sValue.toString().replace( "/", "" );
    sValue = sValue.toString().replace( "(", "" );
    sValue = sValue.toString().replace( "(", "" );
    sValue = sValue.toString().replace( ")", "" );
    sValue = sValue.toString().replace( ")", "" );
    sValue = sValue.toString().replace( " ", "" );
    sValue = sValue.toString().replace( " ", "" );
    fldLen = sValue.length;
    mskLen = sMask.length;

    i = 0;
    nCount = 0;
    sCod = "";
    mskLen = fldLen;

    while (i <= mskLen)
    {
        bolMask = ((sMask.charAt(i) == "-") || (sMask.charAt(i) == ".") || (sMask.charAt(i) == "/"))
        bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")") || (sMask.charAt(i) == " "))

        if (bolMask)
        {
            sCod += sMask.charAt(i);
            mskLen++;
        }
        else
        {
            sCod += sValue.charAt(nCount);
            nCount++;
        }

        i++;
    } // while

    objForm[strField].value = sCod;

    if (nTecla != 8)    // backspace
    {
        if (sMask.charAt(i-1) == "9")   // apenas números...
        {
            return ((nTecla > 47) && (nTecla < 58));    // números de 0 a 9
        }
        else    // qualquer caracter...
        {
            return true;
        }
    }
    else
    {
        return true;
    }
}

//********************************************************************************
// Funcao para aplicar tabulacao automaticamente
//********************************************************************************
var isNN = (navigator.appName.indexOf("Netscape")!=-1);
function autoTab(input, len, e)
{
    var keyCode = (isNN) ? e.which : e.keyCode;
    var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];

    if (input.value.length >= len && !containsElement(filter,keyCode))
    {
        input.value = input.value.slice(0, len);
        input.form[(getIndex(input)+1) % input.form.length].focus();
    }

    function containsElement(arr, ele)
    {
        var found = false, index = 0;
        while (!found && index < arr.length)
            if (arr[index] == ele)
                found = true;
            else
                index++;
        return found;
    }

    function getIndex(input)
    {
        var index = -1, i = 0, found = false;
        while (i < input.form.length && index == -1)
            if (input.form[i] == input)
                index = i;
            else
                i++;
        return index;
    }
    return true;
}

//********************************************************************************
// Funcao para abrir uma nova janela do navegador
//********************************************************************************
function MM_openBrWindow(theURL, winName, features)
{
    window.open(theURL, winName, features);
}

//********************************************************************************
// Funcao para mostrar uma mensagem na barra de status
//********************************************************************************
function MM_displayStatusMsg(msgStr)
{
    status=msgStr;
    document.MM_returnValue = true;
}

//********************************************************************************
// Funcao para validar CPF
//********************************************************************************
function verifica_cpf(formobj, field, msg)
{
    var i;
    var e = formobj.elements[field];
    var s = e.value;
    var c = s.substr(0,9);
    var dv = s.substr(9,2);
    var d1 = 0;
    var invalidos = Array();

    for (var j = 1; j < 10; j++)
    {
        invalidos.push(j*11111111111);
    }
    for (var k = 0; k < invalidos.length; k++)
    {
        if (s == invalidos[k])
        {
            alert(msg + " (1)");
            e.focus();
            e.select();
            return false;
        }
    }

    // 'if' para retirar a obrigatoriedade do CPF
    // na inscricao periodica (apenas na 1ª versao)
    if ((s != "") && (s != null))
    {
        for (i = 0; i < 9; i++)
        {
            d1 += c.charAt(i)*(10-i);
        }
        if (d1 == 0)
        {
            alert(msg + " (2)");
            e.focus();
            e.select();
            return false;
        }

        d1 = 11 - (d1 % 11);
        if (d1 > 9)
            d1 = 0;

        if (dv.charAt(0) != d1)
        {
            alert(msg + " (3)");
            e.focus();
            e.select();
            return false;
        }

        d1 *= 2;
        for (i = 0; i < 9; i++)
        {
            d1 += c.charAt(i)*(11-i);
        }

        d1 = 11 - (d1 % 11);
        if (d1 > 9)
            d1 = 0;

        if (dv.charAt(1) != d1)
        {
            alert(msg + " (4)");
            e.focus();
            e.select();
            return false;
        }

        return true;
    } // if
    else
        return true;
}

//********************************************************************************
// Funcao para verificar e retornar informacoes do navegador
//********************************************************************************

// Ultimate client-side JavaScript client sniff.
// (C) Netscape Communications 1999.  Permission granted to reuse and distribute.
// Revised 17 May 99 to add is.nav5up and is.ie5up (see below).
// Everything you always wanted to know about your JavaScript client
// but were afraid to ask ... "Is" is the constructor function for "is" object,
// which has properties indicating:
// (1) browser vendor:
//     is.nav, is.ie, is.opera
// (2) browser version number:
//     is.major (integer indicating major version number: 2, 3, 4 ...)
//     is.minor (float   indicating full  version number: 2.02, 3.01, 4.04 ...)
// (3) browser vendor AND major version number
//     is.nav2, is.nav3, is.nav4, is.nav4up, is.ie3, is.ie4, is.ie4up, is.ie5, is.ie5up
// (4) JavaScript version number:
//     is.js (float indicating full JavaScript version number: 1, 1.1, 1.2 ...)
// (5) OS platform and version:
//     is.win, is.win16, is.win32, is.win31, is.win95, is.winnt, is.win98
//     is.os2
//     is.mac, is.mac68k, is.macppc
//     is.unix
//        is.sun, is.sun4, is.sun5, is.suni86
//        is.irix, is.irix5, is.irix6
//        is.hpux, is.hpux9, is.hpux10
//        is.aix, is.aix1, is.aix2, is.aix3, is.aix4
//        is.linux, is.sco, is.unixware, is.mpras, is.reliant
//        is.dec, is.sinix, is.freebsd, is.bsd
//     is.vms
//
// See http://www.it97.de/JavaScript/JS_tutorial/bstat/navobj.html and
// http://www.it97.de/JavaScript/JS_tutorial/bstat/Browseraol.html
// for detailed lists of userAgent strings.
//
// Note: you don't want your Nav4 or IE4 code to "turn off" or
// stop working when Nav5 and IE5 (or later) are released, so
// in conditional code forks, use is.nav4up ("Nav4 or greater")
// and is.ie4up ("IE4 or greater") instead of is.nav4 or is.ie4
// to check version in code which you want to work on future
// versions.

function Is ()
{   // convert all characters to lowercase to simplify testing
    var agt=navigator.userAgent.toLowerCase();

    // *** BROWSER VERSION ***
    // Note: On IE5, these return 4, so use is.ie5up to detect IE5.
    this.major = parseInt(navigator.appVersion);
    this.minor = parseFloat(navigator.appVersion);

    this.nav  = ((agt.indexOf('mozilla')!=-1) && (agt.indexOf('spoofer')==-1)
                && (agt.indexOf('compatible') == -1) && (agt.indexOf('opera')==-1)
                && (agt.indexOf('webtv')==-1));
    this.nav2 = (this.nav && (this.major == 2));
    this.nav3 = (this.nav && (this.major == 3));
    this.nav4 = (this.nav && (this.major == 4));
    this.nav4up = (this.nav && (this.major >= 4));
    this.navonly      = (this.nav && ((agt.indexOf(";nav") != -1) ||
                          (agt.indexOf("; nav") != -1)) );
    this.nav5 = (this.nav && (this.major == 5));
    this.nav5up = (this.nav && (this.major >= 5));

    this.ie   = (agt.indexOf("msie") != -1);
    this.ie3  = (this.ie && (this.major < 4));
    this.ie4  = (this.ie && (this.major == 4) && (agt.indexOf("msie 5.0")==-1) );
    this.ie4up  = (this.ie  && (this.major >= 4));
    this.ie5  = (this.ie && (this.major == 4) && (agt.indexOf("msie 5.0")!=-1) );
    this.ie5up  = (this.ie  && !this.ie3 && !this.ie4);

    // KNOWN BUG: On AOL4, returns false if IE3 is embedded browser
    // or if this is the first browser window opened.  Thus the
    // properties is.aol, is.aol3, and is.aol4 aren't 100% reliable.
    this.aol   = (agt.indexOf("aol") != -1);
    this.aol3  = (this.aol && this.ie3);
    this.aol4  = (this.aol && this.ie4);

    this.opera = (agt.indexOf("opera") != -1);
    this.webtv = (agt.indexOf("webtv") != -1);

    // *** JAVASCRIPT VERSION CHECK ***
    if (this.nav2 || this.ie3) this.js = 1.0
    else if (this.nav3 || this.opera) this.js = 1.1
    else if ((this.nav4 && (this.minor <= 4.05)) || this.ie4) this.js = 1.2
    else if ((this.nav4 && (this.minor > 4.05)) || this.ie5) this.js = 1.3
    else if (this.nav5) this.js = 1.4
    // NOTE: In the future, update this code when newer versions of JS
    // are released. For now, we try to provide some upward compatibility
    // so that future versions of Nav and IE will show they are at
    // *least* JS 1.x capable. Always check for JS version compatibility
    // with > or >=.
    else if (this.nav && (this.major > 5)) this.js = 1.4
    else if (this.ie && (this.major > 5)) this.js = 1.3
    // HACK: no idea for other browsers; always check for JS version with > or >=
    else this.js = 0.0;

    // *** PLATFORM ***
    this.win   = ( (agt.indexOf("win")!=-1) || (agt.indexOf("16bit")!=-1) );
    // NOTE: On Opera 3.0, the userAgent string includes "Windows 95/NT4" on all
    //        Win32, so you can't distinguish between Win95 and WinNT.
    this.win95 = ((agt.indexOf("win95")!=-1) || (agt.indexOf("windows 95")!=-1));

    // is this a 16 bit compiled version?
    this.win16 = ((agt.indexOf("win16")!=-1) ||
                  (agt.indexOf("16bit")!=-1) || (agt.indexOf("windows 3.1")!=-1) ||
                  (agt.indexOf("windows 16-bit")!=-1) );

    this.win31 = ((agt.indexOf("windows 3.1")!=-1) || (agt.indexOf("win16")!=-1) ||
                  (agt.indexOf("windows 16-bit")!=-1));

    // NOTE: Reliable detection of Win98 may not be possible. It appears that:
    //       - On Nav 4.x and before you'll get plain "Windows" in userAgent.
    //       - On Mercury client, the 32-bit version will return "Win98", but
    //         the 16-bit version running on Win98 will still return "Win95".
    this.win98 = ((agt.indexOf("win98")!=-1) || (agt.indexOf("windows 98")!=-1));
    this.winnt = ((agt.indexOf("winnt")!=-1) || (agt.indexOf("windows nt")!=-1));
    this.win32 = ( this.win95 || this.winnt || this.win98 ||
                   ((this.major >= 4) && (navigator.platform == "Win32")) ||
                   (agt.indexOf("win32")!=-1) || (agt.indexOf("32bit")!=-1) );

    this.os2   = ((agt.indexOf("os/2")!=-1) ||
                  (navigator.appVersion.indexOf("OS/2")!=-1) ||
                  (agt.indexOf("ibm-webexplorer")!=-1));

    this.mac    = (agt.indexOf("mac")!=-1);
    this.mac68k = (this.mac && ((agt.indexOf("68k")!=-1) ||
                               (agt.indexOf("68000")!=-1)));
    this.macppc = (this.mac && ((agt.indexOf("ppc")!=-1) ||
                               (agt.indexOf("powerpc")!=-1)));

    this.sun   = (agt.indexOf("sunos")!=-1);
    this.sun4  = (agt.indexOf("sunos 4")!=-1);
    this.sun5  = (agt.indexOf("sunos 5")!=-1);
    this.suni86= (this.sun && (agt.indexOf("i86")!=-1));
    this.irix  = (agt.indexOf("irix") !=-1);    // SGI
    this.irix5 = (agt.indexOf("irix 5") !=-1);
    this.irix6 = ((agt.indexOf("irix 6") !=-1) || (agt.indexOf("irix6") !=-1));
    this.hpux  = (agt.indexOf("hp-ux")!=-1);
    this.hpux9 = (this.hpux && (agt.indexOf("09.")!=-1));
    this.hpux10= (this.hpux && (agt.indexOf("10.")!=-1));
    this.aix   = (agt.indexOf("aix") !=-1);      // IBM
    this.aix1  = (agt.indexOf("aix 1") !=-1);
    this.aix2  = (agt.indexOf("aix 2") !=-1);
    this.aix3  = (agt.indexOf("aix 3") !=-1);
    this.aix4  = (agt.indexOf("aix 4") !=-1);
    this.linux = (agt.indexOf("inux")!=-1);
    this.sco   = (agt.indexOf("sco")!=-1) || (agt.indexOf("unix_sv")!=-1);
    this.unixware = (agt.indexOf("unix_system_v")!=-1);
    this.mpras    = (agt.indexOf("ncr")!=-1);
    this.reliant  = (agt.indexOf("reliantunix")!=-1);
    this.dec   = ((agt.indexOf("dec")!=-1) || (agt.indexOf("osf1")!=-1) ||
         (agt.indexOf("dec_alpha")!=-1) || (agt.indexOf("alphaserver")!=-1) ||
         (agt.indexOf("ultrix")!=-1) || (agt.indexOf("alphastation")!=-1));
    this.sinix = (agt.indexOf("sinix")!=-1);
    this.freebsd = (agt.indexOf("freebsd")!=-1);
    this.bsd = (agt.indexOf("bsd")!=-1);
    this.unix  = ((agt.indexOf("x11")!=-1) || this.sun || this.irix || this.hpux ||
                 this.sco ||this.unixware || this.mpras || this.reliant ||
                 this.dec || this.sinix || this.aix || this.linux || this.bsd ||
                 this.freebsd);

    this.vms   = ((agt.indexOf("vax")!=-1) || (agt.indexOf("openvms")!=-1));
}

