﻿

function incluirRegistro(nomeTabela) {
    if (nomeTabela != '') {
        $('#' + nomeTabela + ' tfoot tr:first').clone().appendTo($('#' + nomeTabela + ' tbody'));
        $('#' + nomeTabela + ' tbody tr').each(function (index, row) {
            renomearRow(index, row, nomeTabela);
        });
    }
}



function renomearTabela(nomeTabela) {
    if (nomeTabela != '') {
        $('#' + nomeTabela + ' tbody tr').each(function (index, row) {
            renomearRow(index, row, nomeTabela);
        });
    }
}


function renomearRow(novoIndex, row, nomeTabela) {
    $(row).children().children().each(function (i) {

        if ($(this).is('input') || $(this).is('select') && $(this).attr('Name')) {

            var name = $(this).attr('Name');
            var index = name.substring(name.indexOf('[') + 1, name.indexOf(']'));
            name = name.replace('[' + index + ']', '[' + novoIndex + ']');
            $(this).attr('name', name);

            if ($(this).attr('id')) {
                var id = $(this).attr('id');
                id = id.replace('_' + index + '__', '_' + novoIndex + '__');
                $(this).attr('id', id);
            }

            if ($(this).is('input[type="text"]')) {
                aplicaMascaraUnicoCampo(this);
            }

            if ($(this).is('input[type="button"]')) {
                var comando = $(this).attr('onclick').toString();
                var funcao = comando.substring(comando.indexOf('{') + 1, comando.indexOf('}'));
                alert(comando);
                comando = comando.replace("('" + index + "',", "('" + novoIndex + "',");
                alert(comando);
                $(this).attr('onclick', comando);
            }
        }
    });
}


function aplicaMascarasTodaTabela(nomeTabela) {
    if (nomeTabela != '') {
        $('#' + nomeTabela + ' tbody tr').each(function (index, row) {
            $(row).children().children().each(function () {
                if ($(this).is('input')) {

                    aplicaMascaraUnicoCampo(this);
                }
            });
        });
    }
}

function aplicaMascaraUnicoCampo(campo) {

    if ($(campo).attr('name')) {
        var name = $(campo).attr('name');
        if (name.indexOf('].') >= 0) {
            var tipoCampo = name.substring(name.indexOf('].') + 2);
            if (tipoCampo != '') {
                var mascara;
                if (tipoCampo == 'IP') { mascara = "999.999.999.999"; };
                $(campo).unmask();
                $(campo).mask(mascara);
            }
        }
    }
}




