//<script language=javascript>

function valButton(btn) {
    var cnt = -1;
    for (var i = btn.length - 1; i > -1; i--) {
        if (btn[i].checked) { cnt = i; i = -1; }
    }
    if (cnt > -1) return btn[cnt].value;
    else return null;
}


function isDate(dateStr) {
    var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
    var matchArray = dateStr.match(datePat); // is the format ok?

    if (matchArray == null) {
        return false;
    }
    day = matchArray[1];
    month = matchArray[3]; // p@rse date into variables
    year = matchArray[5];

    if (month < 1 || month > 12) { // check month range
        return false;
    }

    if (day < 1 || day > 31) {
        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;
        }
    }
    return true; // date is valid
}


// Funcao que nao permite o evento Paste no TextBox
function fnBeforePaste() {
    event.returnValue = false;
}

// Verifica preenchimento
function fnVerificaPreenchimento(valor, campo) {
    if (valor == '') {
        alert("O campo '" + campo + "' deverá ser\n preenchido antes da execução\n do cálculo.");
        return '';
    }
}

// Transforma "" em zero
function fnPreencheZero(valor, tipo) {
    if (valor == '' && tipo == '0') {
        return '0';
    }

    else if (valor == '' && tipo == '1') {
        return '0,00';
    }

    else
        return valor;
}

// Verifica preenchimento e formata valor
// Verifica onBlur  
function fnFormataValor(valor) {
    if (valor == '') {
        return '';
    }

    var temp = valor

    if (temp.indexOf(",") == -1) {
        temp = temp.toString() + ',00'
    }
    else {
        var decimal = temp.substr(temp.indexOf(",") + 1)
        if (decimal.length == 0)
            temp = temp.toString() + '00';
        else {
            if (decimal.length == 1)
                temp = temp.toString() + '0';
            else if (decimal.length > 2) {
                temp = parseInt(temp) + temp.substr(temp.indexOf(","), 3);
            }
        }
    }

    return temp
}

// Funcao que verifica se usuario esta digitando numeros e virgula
// Verifica DIGITACAO

function fnPressValor(sValor) {
    var nKey;
    nKey = window.event.keyCode;

    // Transforma ponto em virgula
    if (nKey == 46) {

        if (sValor.indexOf(",") != -1) {
            return false;
        }

        {
            window.event.keyCode = 44;
            return true;
        }
    }

    // Aceita e trata virgula e casas decimais
    else if (nKey == 44) {
        if (sValor.indexOf(",") != -1) {
            return false;
        }

    }
    else {
        if (!(nKey > 47 && nKey < 58)) // nao e' numerico

            return false//;

        //else {
        //if ( sValor.indexOf(",") != -1){

        //	var decimal = sValor.substr(sValor.indexOf(","))
        //	if (decimal.length > 2)
        //	    return false;
        //}
        //}
    }
    //return true;
}


// Funcao que verifica se usuario esta digitando numeros
// Verifica DIGITACAO
function fnPressNumero(sValor) {
    var nKey;
    nKey = window.event.keyCode;

    if (!(nKey > 47 && nKey < 58)) // nao e' numerico

        return false;

}

// Funcao utilitaria que retorna TRUE se a string contiver somente
// espacos em branco

function isblank(s) {

    for (var i = 0; i < s.length; i++) {
        var c = s.charAt(i);
        if ((c != ' ') && (c != '\n') && (c != '\t')) return false;
    }
    return true;
}

// Esta funcao faz a verificao do formulario. Ela sera invocada no evento onSubmit()
// do formulario. O evento recebera desta funcao o valor TRUE or FALSE
// Verifica SUBMIT

function verify(f) {

    var msg;
    var empty_fields = "";
    var errors = "";
    var senha = "";
    var confirma = "";

    // Faz um loop por todos os elementos do formulario, procurando elementos TEXT e 
    // TEXTAREA que nao tem a propriedade 'OPTIONAL' definida. Em seguida, verifica
    // os que estao em branco a faz uma lista deles. Se algum destes elementos tiver
    // um valor minimo ou maximo definido, verifica se foi digitado um numero e
    // se este numero esta dentro do intervalo certo. Por fim, lista todas as mensagens
    // de erro.

    for (var i = 0; i < f.length; i++) {
        var e = f.elements[i];
        // alert (e.name + "\n " + e.type);
        if (((e.type == "text") || (e.type == "textarea") || (e.type == "password")) && !e.optional) {

            // Verifica se o campo esta vazio

            if ((e.value == null) || (e.value == "") || isblank(e.value)) {
                empty_fields += "\n  " + e.legenda;
                continue;
            }

            if (e.name == "txt_Senha") {
                senha = e.value;
            }

            if (e.name == "txt_Confirma") {
                confirma = e.value;
            }

            if (e.eemail == "true") {
                if (e.value.indexOf("@") <= 0) {
                    errors += "- Endereço de e-mail inválido";
                }
            }

            if (e.edata == "true") {
                if (!isDate(e.value)) {
                    errors += "- O campo '" + e.legenda + "' deve ser uma Data válida";
                }
            }

            if (e.value.length < e.minimo) {
                errors += "- O campo '" + e.legenda + "' deve ter no mínimo '" + e.minimo + "' caracteres.\n";
                continue;
            }

            // Verifica campos que devem ser NUMERICOS

            if (e.numeric || (e.min != null) || (e.max != null)) {
                var v = parseFloat(e.value);
                if (isNaN(v) ||
                    ((e.min != null) && (v < e.min)) ||
                    ((e.max != null) && (v > e.max))) {
                    errors += "- O campo '" + e.legenda + "' deve ser um número";
                    if (e.min != null)
                        errors += " maior ou igual a " + e.min;
                    if (e.max != null && e.min != null)
                        errors += " e menor ou igual a " + e.max;
                    else if (e.max != null)
                        errors += " menor ou igual a " + e.max;
                    errors += ".\n";
                }
            }
            if ((senha != "") && (confirma != "")) {
                if (senha != confirma) {
                    errors += "- Senha e Confirmação não conferem.\n";
                }
            }


            // Verifica se a data final da vigência é maior que a data atual

            if (e.id == "f_date_vigant") {

                var tmpVig = e.value; //'29/01/1982'

                var dt1 = tmpVig.substring(0, 2);
                var mon1 = tmpVig.substring(3, 5);
                var yr1 = tmpVig.substring(6, 10);

                if (isDate(tmpVig)) {

                    var myDate = yr1 + mon1 + dt1;

                    var today = new Date();
                    var dd = today.getDate();
                    var mm = today.getMonth() + 1; //January is 0!
                    var yyyy = today.getFullYear();
                    if (dd < 10) { dd = '0' + dd }
                    if (mm < 10) { mm = '0' + mm }

                    var todayDate = yyyy + mm + dd;

                    //alert('myDate:' + myDate);
                    //alert('todayDate:' + todayDate);

                    if (myDate <= todayDate) {
                        errors += "- O campo '" + e.legenda + "' deve conter uma data maior que a data de hoje.\n";
                    }
                }
            }

        }
        else if ((e.type == "select-one") && (!e.optional)) {
            //alert("Valor:" + e.value);
            if ((e.value == null) || (e.value == "") || isblank(e.value) || (e.value == "0")) {
                empty_fields += "\n  " + e.legenda;
                continue;
            }
        }
    }

    // Agora, se houver algum erro, exibe a mensagem e retorna FALSE para evitar
    // que o Formulario seja submetido. Caso contrario retorna TRUE
    if (!empty_fields && !errors) return true;

    msg = "________________________________________________________________\n\n"
    msg += "Para finalizar a operação, por favor corrija os seguintes erros e tente novamente:\n"
    msg += "________________________________________________________________\n\n"

    if (empty_fields) {
        msg += "- Os campos abaixo devem ser preenchidos:\n " + empty_fields + "\n";
        if (errors) msg += "\n";
    }
    msg += errors;
    alert(msg)
    return false;
}
        


