/* Minification failed. Returning unminified contents.
(2,23): run-time error CSS1031: Expected selector, found '='
(2,23): run-time error CSS1025: Expected comma or open brace, found '='
(3,21): run-time error CSS1031: Expected selector, found '='
(3,21): run-time error CSS1025: Expected comma or open brace, found '='
(7,1): run-time error CSS1019: Unexpected token, found '$'
(7,2): run-time error CSS1019: Unexpected token, found '('
(7,11): run-time error CSS1031: Expected selector, found ')'
(7,11): run-time error CSS1025: Expected comma or open brace, found ')'
(25,2): run-time error CSS1019: Unexpected token, found ')'
(35,10): run-time error CSS1031: Expected selector, found 'consultarAlertaTipoComprobanteHasTipoDocumentoDIAN('
(35,10): run-time error CSS1025: Expected comma or open brace, found 'consultarAlertaTipoComprobanteHasTipoDocumentoDIAN('
(85,10): run-time error CSS1031: Expected selector, found 'consultarAlertaTipoComprobanteResolucionDIAN('
(85,10): run-time error CSS1025: Expected comma or open brace, found 'consultarAlertaTipoComprobanteResolucionDIAN('
(120,10): run-time error CSS1031: Expected selector, found 'SetSelect2TerceroForTipoComprobante('
(120,10): run-time error CSS1025: Expected comma or open brace, found 'SetSelect2TerceroForTipoComprobante('
(139,10): run-time error CSS1031: Expected selector, found 'SetSelect2Tercero('
(139,10): run-time error CSS1025: Expected comma or open brace, found 'SetSelect2Tercero('
(164,10): run-time error CSS1031: Expected selector, found 'CrearAutocompletarSelect2ByFilterCommon('
(164,10): run-time error CSS1025: Expected comma or open brace, found 'CrearAutocompletarSelect2ByFilterCommon('
(203,10): run-time error CSS1031: Expected selector, found 'formatRepoAutocompletarSelect2('
(203,10): run-time error CSS1025: Expected comma or open brace, found 'formatRepoAutocompletarSelect2('
(231,10): run-time error CSS1031: Expected selector, found 'GetTd('
(231,10): run-time error CSS1025: Expected comma or open brace, found 'GetTd('
(235,10): run-time error CSS1031: Expected selector, found 'GetTdRight('
(235,10): run-time error CSS1025: Expected comma or open brace, found 'GetTdRight('
(239,10): run-time error CSS1031: Expected selector, found 'GetTdText('
(239,10): run-time error CSS1025: Expected comma or open brace, found 'GetTdText('
(264,10): run-time error CSS1031: Expected selector, found 'GetTdSelect('
(264,10): run-time error CSS1025: Expected comma or open brace, found 'GetTdSelect('
(270,10): run-time error CSS1031: Expected selector, found 'GetTdInputCurrency('
(270,10): run-time error CSS1025: Expected comma or open brace, found 'GetTdInputCurrency('
(275,10): run-time error CSS1031: Expected selector, found 'GetHidden('
(275,10): run-time error CSS1025: Expected comma or open brace, found 'GetHidden('
(279,10): run-time error CSS1031: Expected selector, found 'GetHiddenNameValue('
(279,10): run-time error CSS1025: Expected comma or open brace, found 'GetHiddenNameValue('
(290,10): run-time error CSS1031: Expected selector, found 'ValidarTextoNoVacio('
(290,10): run-time error CSS1025: Expected comma or open brace, found 'ValidarTextoNoVacio('
(302,10): run-time error CSS1031: Expected selector, found 'isNullOrWhiteSpace('
(302,10): run-time error CSS1025: Expected comma or open brace, found 'isNullOrWhiteSpace('
(312,10): run-time error CSS1031: Expected selector, found 'isNullOrWhiteSpaceByFiledId('
(312,10): run-time error CSS1025: Expected comma or open brace, found 'isNullOrWhiteSpaceByFiledId('
(325,10): run-time error CSS1031: Expected selector, found 'isNullOrWhiteSpaceOrZeroOrNegativeNumberByFiledId('
(325,10): run-time error CSS1025: Expected comma or open brace, found 'isNullOrWhiteSpaceOrZeroOrNegativeNumberByFiledId('
(340,10): run-time error CSS1031: Expected selector, found 'isNullOrWhiteSpaceOrZeroOrNegativeNumber('
(340,10): run-time error CSS1025: Expected comma or open brace, found 'isNullOrWhiteSpaceOrZeroOrNegativeNumber('
(363,10): run-time error CSS1031: Expected selector, found 'isPositiveNumber('
(363,10): run-time error CSS1025: Expected comma or open brace, found 'isPositiveNumber('
(390,10): run-time error CSS1031: Expected selector, found 'isPositiveInteger('
(390,10): run-time error CSS1025: Expected comma or open brace, found 'isPositiveInteger('
(405,10): run-time error CSS1031: Expected selector, found 'getValueOrNullIfEmpty('
(405,10): run-time error CSS1025: Expected comma or open brace, found 'getValueOrNullIfEmpty('
(421,10): run-time error CSS1031: Expected selector, found 'ValidarFormulario('
(421,10): run-time error CSS1025: Expected comma or open brace, found 'ValidarFormulario('
(442,10): run-time error CSS1031: Expected selector, found 'OcultarElementos('
(442,10): run-time error CSS1025: Expected comma or open brace, found 'OcultarElementos('
(449,10): run-time error CSS1031: Expected selector, found 'toArray('
(449,10): run-time error CSS1025: Expected comma or open brace, found 'toArray('
(461,15): run-time error CSS1031: Expected selector, found '='
(461,15): run-time error CSS1025: Expected comma or open brace, found '='
(465,2): run-time error CSS1019: Unexpected token, found ')'
(467,10): run-time error CSS1031: Expected selector, found 'ValidaLista('
(467,10): run-time error CSS1025: Expected comma or open brace, found 'ValidaLista('
(474,10): run-time error CSS1031: Expected selector, found 'ValidaNumero('
(474,10): run-time error CSS1025: Expected comma or open brace, found 'ValidaNumero('
(483,10): run-time error CSS1031: Expected selector, found 'seleccionarFila('
(483,10): run-time error CSS1025: Expected comma or open brace, found 'seleccionarFila('
(487,10): run-time error CSS1031: Expected selector, found 'quitarSeleccionadoTablaImputacion('
(487,10): run-time error CSS1025: Expected comma or open brace, found 'quitarSeleccionadoTablaImputacion('
(495,10): run-time error CSS1031: Expected selector, found 'borrarMensaje('
(495,10): run-time error CSS1025: Expected comma or open brace, found 'borrarMensaje('
(502,10): run-time error CSS1031: Expected selector, found 'borrarMensajeImputacion('
(502,10): run-time error CSS1025: Expected comma or open brace, found 'borrarMensajeImputacion('
(506,10): run-time error CSS1031: Expected selector, found 'borrarMensajeContabilidad('
(506,10): run-time error CSS1025: Expected comma or open brace, found 'borrarMensajeContabilidad('
(514,10): run-time error CSS1031: Expected selector, found 'quitarRowImputacion('
(514,10): run-time error CSS1025: Expected comma or open brace, found 'quitarRowImputacion('
(522,10): run-time error CSS1031: Expected selector, found 'calcularTotalImputaciones('
(522,10): run-time error CSS1025: Expected comma or open brace, found 'calcularTotalImputaciones('
(535,10): run-time error CSS1031: Expected selector, found 'select2Cuentas('
(535,10): run-time error CSS1025: Expected comma or open brace, found 'select2Cuentas('
(575,14): run-time error CSS1031: Expected selector, found '='
(575,14): run-time error CSS1025: Expected comma or open brace, found '='
(576,1): run-time error CSS1019: Unexpected token, found '$'
(576,23): run-time error CSS1030: Expected identifier, found 'set('
(576,23): run-time error CSS1031: Expected selector, found 'set('
(576,23): run-time error CSS1025: Expected comma or open brace, found 'set('
(577,1): run-time error CSS1019: Unexpected token, found '$'
(577,23): run-time error CSS1030: Expected identifier, found 'set('
(577,23): run-time error CSS1031: Expected selector, found 'set('
(577,23): run-time error CSS1025: Expected comma or open brace, found 'set('
(578,1): run-time error CSS1019: Unexpected token, found '$'
(578,23): run-time error CSS1030: Expected identifier, found 'set('
(578,23): run-time error CSS1031: Expected selector, found 'set('
(578,23): run-time error CSS1025: Expected comma or open brace, found 'set('
(579,1): run-time error CSS1019: Unexpected token, found '$'
(579,23): run-time error CSS1030: Expected identifier, found 'set('
(579,23): run-time error CSS1031: Expected selector, found 'set('
(579,23): run-time error CSS1025: Expected comma or open brace, found 'set('
(580,1): run-time error CSS1019: Unexpected token, found '$'
(580,23): run-time error CSS1030: Expected identifier, found 'set('
(580,23): run-time error CSS1031: Expected selector, found 'set('
(580,23): run-time error CSS1025: Expected comma or open brace, found 'set('
(582,10): run-time error CSS1031: Expected selector, found 'select2('
(582,10): run-time error CSS1025: Expected comma or open brace, found 'select2('
(615,16): run-time error CSS1031: Expected selector, found '='
(615,16): run-time error CSS1025: Expected comma or open brace, found '='
(616,10): run-time error CSS1031: Expected selector, found 'formatRepo('
(616,10): run-time error CSS1025: Expected comma or open brace, found 'formatRepo('
(643,10): run-time error CSS1031: Expected selector, found 'ValidarTextoNoVacioCommon('
(643,10): run-time error CSS1025: Expected comma or open brace, found 'ValidarTextoNoVacioCommon('
(657,10): run-time error CSS1031: Expected selector, found 'HabilitarBtnCargarPorArchivo('
(657,10): run-time error CSS1025: Expected comma or open brace, found 'HabilitarBtnCargarPorArchivo('
(673,10): run-time error CSS1031: Expected selector, found 'jsonHasErrorMessage('
(673,10): run-time error CSS1025: Expected comma or open brace, found 'jsonHasErrorMessage('
(688,10): run-time error CSS1031: Expected selector, found 'HabilitarControlesPorContenedor('
(688,10): run-time error CSS1025: Expected comma or open brace, found 'HabilitarControlesPorContenedor('
(714,2): run-time error CSS1031: Expected selector, found 'function('
(714,2): run-time error CSS1025: Expected comma or open brace, found 'function('
(714,3682): run-time error CSS1019: Unexpected token, found '('
(714,3689): run-time error CSS1031: Expected selector, found ')'
(714,3689): run-time error CSS1025: Expected comma or open brace, found ')'
(725,1): run-time error CSS1019: Unexpected token, found '!'
(725,2): run-time error CSS1019: Unexpected token, found 'function('
(725,12): run-time error CSS1031: Expected selector, found ')'
(725,12): run-time error CSS1025: Expected comma or open brace, found ')'
(725,7878): run-time error CSS1019: Unexpected token, found '('
(725,7892): run-time error CSS1031: Expected selector, found ')'
(725,7892): run-time error CSS1025: Expected comma or open brace, found ')'
 */
//variables select2
var searchTermSelect2 = null;
var pageSizeSelect2 = 20;

//// Metodos Comunes ////

$(document).ready(function () {
    $("input").focus(function () { $(this).select(); });


    select2("#TerceroId", "--Seleccione Tercero--", "Contabilidad/Terceros/BuscarTercerosSelect2");

    $("#TipoComprobanteId").change(function () {
        consultarAlertaTipoComprobanteHasTipoDocumentoDIAN();
    });

    $("#TipoComprobanteId").change();

    $('.input-alphanumeric').on('input', function () {
        this.value = this.value.replace(/[^A-Za-z0-9]/g, '');
    });
    $('.input-numeric').on('input', function () {
        this.value = this.value.replace(/[^0-9]/g, '');
    });
});

/**
 * @function consultarAlertaTipoComprobanteHasTipoDocumentoDIAN
 * @description Realiza una consulta AJAX para verificar si el tipo de comprobante seleccionado tiene asociado un tipo de documento DIAN y si cuenta con autorización DIAN configurada.
 * Muestra mensajes de error utilizando SweetAlert2 si ocurre algún problema o si la configuración no es válida.
 * Si el tipo de comprobante tiene autorización DIAN, realiza una consulta adicional para mostrar la alerta de resolución DIAN.
 * @author scl
 * @date 09/Jul/2025.
 */
function consultarAlertaTipoComprobanteHasTipoDocumentoDIAN() {
    // Verifica si el campo TipoComprobanteId está vacío o solo contiene espacios en blanco
    if (isNullOrWhiteSpace($('#TipoComprobanteId').val())) {
        return;
    }

    // Prepara el array de datos JSON a enviar en la petición
    const jsonArray = [
        { tipoComprobanteId: $('#TipoComprobanteId').val() },
    ];

    // Define la URL del endpoint que realizará la validación en el servidor
    const url = window.rootUrl + 'Contabilidad/TiposComprobantes/ConsultarAlertaTipoComprobanteHasTipoDocumentoDIAN';

    /**
     * @function manejarRespuestaTipoDocumentoDIAN
     * @description Maneja la respuesta de la consulta al servidor.
     * Muestra un mensaje de error si la consulta no fue exitosa, o realiza una consulta adicional si el tipo de comprobante tiene autorización DIAN.
     * @param {Object} response - Respuesta recibida del servidor.
     */
    function manejarRespuestaTipoDocumentoDIAN(response) {
        // Si la respuesta indica error, muestra el mensaje correspondiente y limpia el campo
        if (!response.Success) {
            if (!isNullOrWhiteSpace(response.Message)) {
                showMessage(response.Message, MESSAGE_SEVERITIES.ERROR);
            } else {
                showMessage('Error al consultar configuración DIAN para tipo de comprobante. Por favor informe al área de sistemas', MESSAGE_SEVERITIES.ERROR);
            }
            // Limpia el campo de selección de tipo de comprobante
            $("#TipoComprobanteId").val(null).change();
        } else {
            // Si el tipo de comprobante tiene autorización DIAN, consulta la alerta de resolución DIAN
            if (response.Data.tipoComprobanteHasAutorizacionDIAN) {
                consultarAlertaTipoComprobanteResolucionDIAN();
            }
        }
    }

    // Envía la petición AJAX utilizando la función utilitaria definida en commonUtils.js
    sendJsonArrayAndHandleResponse(jsonArray, url, manejarRespuestaTipoDocumentoDIAN);
}


/**
 * Consultar por ajax alerta resolución DIAN tipo comprobante.
 * Autor: scl.
 * Fecha: 
 * Fecha modificación: none.
 * Modificado por: none.
 */
function consultarAlertaTipoComprobanteResolucionDIAN() {
    let ajaxSettings = {};

    //limpia contenedor de la vista parcial
    $("#DivAlert").empty();

    if (isNullOrWhiteSpace($('#TipoComprobanteId').val())) {
        return;
    }

    ProcesandoTarea();
    ajaxSettings.url = window.rootUrl + "Contabilidad/TiposComprobantes/ConsultarAlertaTipoComprobanteHasAutorizacionDIAN";
    ajaxSettings.type = "POST";
    ajaxSettings.data = {
        tipoComprobanteId: $('#TipoComprobanteId').val(),
    };
    ajaxSettings.success = function (response) {
        $("#DivAlert").html(response);
        TareaFinalizada();
    };
    ajaxSettings.error = function () {
        alert("Error al consultar configuración del comprobante en el servidor. Por favor informe al área de sistemas");
        TareaFinalizada();
    };
    $.ajax(ajaxSettings);
}

/**
 * Setea select2 para terceros filtrando por tipo comprobante.
 * Autor: scl.
 * Fecha: 
 * Fecha modificación: none.
 * Modificado por: none.
 * @param tipoComprobanteId
 */
function SetSelect2TerceroForTipoComprobante(tipoComprobanteId) {
    CrearAutocompletarSelect2ByFilterCommon(
        "TerceroId",
        'Contabilidad/Terceros/GetTercerosByFilterAsJSONForSelect2',
        '-Seleccione-',
        {
            TipoComprobanteId: tipoComprobanteId,
            FiltraParaTipoComprobante: true,
        }
    );
}

/**
 * Setea select2 para terceros.
 * Autor: scl.
 * Fecha: 
 * Fecha modificación: none.
 * Modificado por: none.
 */
function SetSelect2Tercero() {
    //select2 terceros
    let _filtraTerceroPorTipoComprobante = typeof filtraTerceroPorTipoComprobante !== 'undefined' && filtraTerceroPorTipoComprobante;

    let tipoComprobanteId = $('#TipoComprobanteId').val();
    let existsTipoComprobanteId = !isNullOrWhiteSpace(tipoComprobanteId);

    if (_filtraTerceroPorTipoComprobante && existsTipoComprobanteId) {
        SetSelect2TerceroForTipoComprobante(tipoComprobanteId);
    } else {
        select2("#TerceroId", "--Seleccione Tercero--", "Contabilidad/Terceros/BuscarTercerosSelect2");
    }
}

//Autocompletar
/**
 * Crea autocompletar mediante petición POST
 * En atributo filter se pasa el filtro determinado para cada select2 en la funcion ajax del controlador.
 * Autor: scl.
 * Fecha: 
 * @param selectFieldID
 * @param url
 * @param placeholder
 * @param filter
 */
function CrearAutocompletarSelect2ByFilterCommon(selectFieldID, url, placeholder, filter) {
    $('#' + selectFieldID).select2({
        placeholder: placeholder,
        allowClear: placeholder != "" && placeholder != null ? true : false,
        ajax: {
            delay: 350,
            url: window.rootUrl + url,
            type: "POST",
            dataType: 'json',
            data: function (params) {
                searchTermSelect2 = params.term,
                    params.page = params.page || 1;
                return {
                    searchTerm: params.term,
                    pageSize: pageSizeSelect2,
                    pageNumber: params.page,
                    filter: filter
                };
            },
            processResults: function (data, params) {
                if (data.hasOwnProperty('ErrorMessage') && typeof data.ErrorMessage !== 'undefined' &&
                    data.ErrorMessage != null && data.ErrorMessage.toString().trim().length > 0) {
                    alert(data.ErrorMessage);
                } else {
                    params.page = params.page || 1;
                    return {
                        results: data.Results,
                        pagination: {
                            more: (params.page * pageSizeSelect2) < data.Total
                        }
                    };
                }
            }
        },
        escapeMarkup: function (markup) { return markup; },
        templateResult: formatRepoAutocompletarSelect2
    });
}

function formatRepoAutocompletarSelect2(repo) {
    if (repo.loading)
        return repo.text;

    var text = "";
    if (repo.textFormato != null)
        text = repo.textFormato;
    else
        text = repo.text;

    if (typeof searchTermSelect2 != 'undefined' && searchTermSelect2 != null && searchTermSelect2 != "") {
        var match = -1;
        searchTermSelect2 = searchTermSelect2.replace("|", "");
        match = text.toUpperCase().indexOf(searchTermSelect2.toUpperCase());
        if (match >= 0) {
            var subText = text.substring(match, match + searchTermSelect2.length);
            text = text.replace(new RegExp(subText, 'g'), "<b><u>" + subText + "</u></b>");
        }
    }
    return text;
}
//////////////////////////////////////////////////////


//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

//// Funciones Tablas ////

function GetTd(object, texto) {
    return GetTdText(object, texto).append(GetHidden(object));
}

function GetTdRight(object, texto) {
    return GetTdText(object, texto, "text-align: right").append(GetHidden(object));
}

function GetTdText(object, texto, right) {
    var style = "";
    if (right != undefined) {
        style = right;
    }

    if (object.is("input")) {
        if (object.hasClass("currency")) {
            style = "text-align: right";
            texto = formatter.format(object.val());
        }
        else if (typeof texto === 'undefined')
            texto = object.val();
    }
    else if (object.is("textarea")) {
        texto = object.text();
    }
    else if (object.is("select")) {
        if (typeof texto === 'undefined')
            texto = object.find("option:selected").text();
    }

    return $('<td>').attr('style', style).append(texto);
}

function GetTdSelect(select) {
    return $('<td>')
        .append($('<text id="' + select.attr('id') + 'Text">').append(select.find("option:selected").text()))
        .append(GetHidden(select));
}

function GetTdInputCurrency(object) {
    var texto = formatter.format(object.val());
    return $('<td>').attr('style', 'text-align: right').append(texto).append(GetHidden(object));
}

function GetHidden(object) {
    return $("<input type='hidden' id='" + object.attr('id') + "' name='" + object.attr('name') + "[]' value='" + object.val() + "' />");
}

function GetHiddenNameValue(name, value) {
    return $("<input type='hidden' id='" + name + "' name='" + name + "[]' value='" + value + "' />");
}

//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

/**
 * Valida que una cadena de texto no este vacia y no contenga caracteres que sean solo espacios en blanco. 
 * Autor: scl
 * Fecha: 
 */
function ValidarTextoNoVacio(texto) {
    if (texto !== undefined && texto != null && texto !== "" && texto.toString().trim().length > 0)
        return true;
    return false;
}

/**
 * Valida que una cadena de texto  este vacia o contenga caracteres que sean solo espacios en blanco. 
 * Autor: scl
 * Fecha: 
 * @param texto string - texto que es validado.
 */
function isNullOrWhiteSpace(texto) {
    if (ValidarTextoNoVacio(texto))
        return false;
    return true;
}

/**
 * Modificado por: none.
 * @param fieldId string - id del campo que contiene el texto.
 */
function isNullOrWhiteSpaceByFiledId(fieldId) {
    return isNullOrWhiteSpace($(`#${fieldId}`).val());
}


/**
 * Valida que una cadena de texto  este vacia o contenga caracteres que sean solo espacios en blanco O sea valor numérico menor a cero. 
 * Autor: scl
 * Fecha: 
 * Fecha de modificación: none.
 * Modificado por: none.
 * @param fieldId string - id del campo que contiene el texto.
 */
function isNullOrWhiteSpaceOrZeroOrNegativeNumberByFiledId(fieldId) {

    let value = $(`#${fieldId}`).val();

    return isNullOrWhiteSpaceOrZeroOrNegativeNumber(value);
}

/**
 * Valida que una cadena de texto  este vacia o contenga caracteres que sean solo espacios en blanco O sea valor numérico menor a cero. 
 * Autor: scl
 * Fecha: 
 * Fecha de modificación: none.
 * Modificado por: none.
 * @param value string.
 */
function isNullOrWhiteSpaceOrZeroOrNegativeNumber(value) {
    let numberValue;

    if (isNullOrWhiteSpace(value)) {
        return true;
    }
    numberValue = Number.parseFloat(value);

    if (Number.isNaN(numberValue)) {
        return false;
    }

    if (numberValue <= 0) {
        return true;
    }
    return false;
}

/**
 * Autor: scl
 * Fecha: 17/Mar/2025.
 * @param value string - id del campo que contiene el texto.
 */
function isPositiveNumber(value) {
    let numberValue;

    if (isNullOrWhiteSpace(value)) {
        return false;
    }

    if (isNaN(value)) {
        return false;
    }

    numberValue = parseFloat(value);

    if (numberValue > 0) {
        return true;
    }

    return false;
}

/**
 * Autor: scl
 * Fecha: 19/Abr/2025.
 * Verifica si un número es positivo y entero.
 * @param {string|number} value - El valor a verificar.
 * @returns {boolean} - Retorna true si el número es positivo y entero, de lo contrario false.
 */
function isPositiveInteger(value) {
    if (!isPositiveNumber(value)) {
        return false;
    }

    let numberValue = Number.parseFloat(value);
    return Number.isInteger(numberValue);
}

/**
 * Obtiene valor de campo. Si es nulo o vacío retorna null. 
 * Autor: scl
 * Fecha: 
 * @param fieldId string.
 */
function getValueOrNullIfEmpty(fieldId) {
    let value = $('#' + fieldId).val();
    if (isNullOrWhiteSpace(value))
        return null;
    return value;
}

/**
 * Valida el formulario especificado y oculta elementos del contenedor especificado
 * Si el formulario no se envia por tener datos invalidos, vuelve a mostrar dichos elementos
 * Autor: scl
 * Fecha de modificación: 
 * Modificado por: scl.
 * @param idFormulario string - id del formulario que se envia por ajax
 * @param idContenedorOculta string - id del contenedor que  se va a ocultar mientras se valida y envia la informacion.
 */
function ValidarFormulario(idFormulario, idContenedorOculta = "elementos_ocultar_container") {
    OcultarElementos(idContenedorOculta, true);
    expandirSeccionesValidar(idFormulario);
    if (!$('#' + idFormulario).valid()) {
        //visualiza mensajes validacion errores
        $(".validation-summary-errors").show();
        $('#' + idContenedorOculta).show();
        TareaFinalizada();
        contraerSeccionesValidar();
        return false;
    }
    $('#' + idFormulario).submit();
    return true;
}

/**
 * Oculta elementos del contenedor especificado. 
 * Autor: scl
 * @param idContenedor string - id del formulario que se envia por ajax
 * @param mostrarProcesandoTarea bool - determina si se muestra barra superior con el mensaje de procesando tarea
 */
function OcultarElementos(idContenedor, mostrarProcesandoTarea) {
    $('#' + idContenedor).hide();
    if (mostrarProcesandoTarea) {
        ProcesandoTarea();
    }
}

function toArray(objName) {
    var listObj = document.getElementsByName(objName);
    var listResult = [];
    for (i = 0; i < listObj.length; i++) {
        if (listObj[i].type == "checkbox")
            listResult.push((listObj[i]).checked);
        else
            listResult.push(listObj[i].value);
    }
    return listResult;
}

var formatter = new Intl.NumberFormat("en-US", {
    //style: "currency",
    //currency: "USD",
    minimumFractionDigits: 2
});

function ValidaLista(fieldName) {
    if ($("#" + fieldName).val() == null || $("#" + fieldName).val() == "" || isNaN($("#" + fieldName).val())) {
        return false;
    }
    return true;
}

function ValidaNumero(fieldName) {
    if ($("#" + fieldName).val() == "" || isNaN($("#" + fieldName).val()) || Number($("#" + fieldName).val()) <= 0) {
        return false;
    }
    return true;
}

///////////

function seleccionarFila(row) {
    row.parentNode.parentNode.style.color = 'rgb(49, 204, 10)';
}

function quitarSeleccionadoTablaImputacion() {
    $("#tablaImputacion tbody tr").each(function () {
        $(this).css("color", "");
    });
}

///////////

function borrarMensaje(tabla, mensaje) {
    try {
        document.getElementById(table).deleteRow(document.getElementById(mensaje).rowIndex);
    }
    catch (err) { }
}

function borrarMensajeImputacion() {
    borrarMensaje("tablaImputacion", "message");
}

function borrarMensajeContabilidad() {
    borrarMensaje("tablaContabilidad", "MessageContabilidad");
}

//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

//// Metodos Imputaciones ////

function quitarRowImputacion(row) {
    borrarMensajeImputacion();
    //
    var index = row.parentNode.parentNode.rowIndex;
    document.getElementById("tablaImputacion").deleteRow(index);
    calcularTotalImputaciones();
}

function calcularTotalImputaciones() {
    var listValor = document.getElementsByName("ListValor");
    var total = 0;
    for (i = 0; i < listValor.length; i++) {
        total += Number(listValor[i].value);
    }
    $("#totalImputacion").html(formatter.format(total));
}

//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

//// Select 2 para cuentas contables ////

function select2Cuentas(object, usoCuenta, detalleCartera, cuentaId = 0) {
    var optionListUrl = window.rootUrl + "Contabilidad/DetallesContabilidad/BuscarCuentasSelect2";
    $(object).select2({
        placeholder: "--Seleccione Cuenta--",
        allowClear: true,
        ajax: {
            delay: 350,
            url: optionListUrl,
            dataType: 'json',
            data: function (params) {
                searchTerm = params.term,
                    params.page = params.page || 1;
                return {
                    searchTerm: params.term,
                    pageSize: pageSize,
                    pageNumber: params.page,
                    usoCuenta: usoCuenta,
                    detalleCartera: detalleCartera,
                    cuentaId: cuentaId,
                };
            },
            processResults: function (data, params) {
                params.page = params.page || 1;
                return {
                    results: data.Results,
                    pagination: {
                        more: (params.page * pageSize) < data.Total
                    }
                };
            }
        },
        escapeMarkup: function (markup) { return markup; },
        templateResult: formatRepo
    });
}

//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

//// SELECT2 ////

var pageSize = 30;
$.fn.select2.defaults.set("language", "es");
$.fn.select2.defaults.set("minimumResultsForSearch", "0");
$.fn.select2.defaults.set("minimumInputLength", "0");
$.fn.select2.defaults.set("width", '100%');
$.fn.select2.defaults.set("allowClear", false);

function select2(object, placeholder, url) {
    var optionListUrl = window.rootUrl + url;
    $(object).select2({
        placeholder: placeholder,
        allowClear: placeholder != "" ? true : false,
        ajax: {
            delay: 350,
            url: optionListUrl,
            dataType: 'json',
            data: function (params) {
                searchTerm = params.term,
                    params.page = params.page || 1;
                return {
                    searchTerm: params.term,
                    pageSize: pageSize,
                    pageNumber: params.page
                };
            },
            processResults: function (data, params) {
                params.page = params.page || 1;
                return {
                    results: data.Results,
                    pagination: {
                        more: (params.page * pageSize) < data.Total
                    }
                };
            }
        },
        escapeMarkup: function (markup) { return markup; },
        templateResult: formatRepo
    });
}

var searchTerm = null;
function formatRepo(repo) {
    if (repo.loading)
        return repo.text;

    var text = "";
    if (repo.textFormato != null)
        text = repo.textFormato;
    else
        text = repo.text;

    if (typeof searchTerm != 'undefined' && searchTerm != null && searchTerm != "") {
        var match = -1;
        searchTerm = searchTerm.replace("|", "");
        match = text.toUpperCase().indexOf(searchTerm.toUpperCase());
        if (match >= 0) {
            var subText = text.substring(match, match + searchTerm.length);
            text = text.replace(new RegExp(subText, 'g'), "<b><u>" + subText + "</u></b>");
        }
    }
    return text;
}

/**
 * Valida que una cadena de texto no este vacia y no contenga caracteres que sean solo espacios en blanco. 
 * Autor: scl
 * Fecha: 
 */
function ValidarTextoNoVacioCommon(texto) {
    if (texto != null && texto != "" && texto.toString().trim().length > 0)
        return true;
    return false;
}

/**
 * Autor: scl.
 * Fecha: 
 * Fecha modificación: none.
 * Modificado por: none.
 * @param {string} inputFileId Id input file.
 * @param {string} cargarButtonId Id botón cargar.
 */
function HabilitarBtnCargarPorArchivo(inputFileId, cargarButtonId) {
    if ($('#' + inputFileId).val() != null && $('#' + inputFileId).val() != "") {
        $('#' + cargarButtonId).removeAttr('disabled');
    }
    else {
        $('#' + cargarButtonId).attr('disabled', 'disabled');
    }
}

/**
 * Autor: scl.
 * Fecha: 
 * Fecha modificacion: none.
 * Modificado por: none.
 * @param json
 */
function jsonHasErrorMessage(json) {
    return (json.hasOwnProperty('ErrorMessage') && typeof json.ErrorMessage !== 'undefined' &&
        !isNullOrWhiteSpace(json.ErrorMessage)) ||
        (json.hasOwnProperty('errorMessage') && typeof json.errorMessage !== 'undefined' &&
            !isNullOrWhiteSpace(json.errorMessage))
}

/**
 * Habilita / deshabilita controles pertenecientes a un contenedor.
 * Autor: scl.
 * Fecha modificación: 
 * @param idContenedor string - id del contenedor.
 * @param habilitar bool - true => habilita; false => deshabilita
 * @param limpiar bool - en caso de deshabilitar, si este valor es true, entonces limpia los campos.
 */
function HabilitarControlesPorContenedor(idContenedor, habilitar, limpiar, ocultar = false) {
    $("#" + idContenedor).find('input, textarea, button, select').attr("disabled", !habilitar);
    if (!habilitar) {
        if (limpiar) {
            $("#" + idContenedor).find("input[type = 'number']").val("");
            $("#" + idContenedor).find('select').val('').trigger("change");
            $("#" + idContenedor).find('input:text, textarea').val("");
            $("#" + idContenedor).find('input[type = datetime]').val("");
            $("#" + idContenedor).find('input:checkbox').prop('checked', false);
            $("#" + idContenedor).find('input:radio').prop('checked', false);
        }
        if (ocultar) {
            $("#" + idContenedor).hide();
        }
    } else {
        $("#" + idContenedor).show();
    }
}

/*! ========================================================================
 * Bootstrap Toggle: bootstrap-toggle.js v2.2.0
 * http://www.bootstraptoggle.com
 * ========================================================================
 * Copyright 2014 Min Hur, The New York Times Company
 * Licensed under MIT
 * ======================================================================== */
+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.toggle"),f="object"==typeof b&&b;e||d.data("bs.toggle",e=new c(this,f)),"string"==typeof b&&e[b]&&e[b]()})}var c=function(b,c){this.$element=a(b),this.options=a.extend({},this.defaults(),c),this.render()};c.VERSION="2.2.0",c.DEFAULTS={on:"On",off:"Off",onstyle:"primary",offstyle:"default",size:"normal",style:"",width:null,height:null},c.prototype.defaults=function(){return{on:this.$element.attr("data-on")||c.DEFAULTS.on,off:this.$element.attr("data-off")||c.DEFAULTS.off,onstyle:this.$element.attr("data-onstyle")||c.DEFAULTS.onstyle,offstyle:this.$element.attr("data-offstyle")||c.DEFAULTS.offstyle,size:this.$element.attr("data-size")||c.DEFAULTS.size,style:this.$element.attr("data-style")||c.DEFAULTS.style,width:this.$element.attr("data-width")||c.DEFAULTS.width,height:this.$element.attr("data-height")||c.DEFAULTS.height}},c.prototype.render=function(){this._onstyle="btn-"+this.options.onstyle,this._offstyle="btn-"+this.options.offstyle;var b="large"===this.options.size?"btn-lg":"small"===this.options.size?"btn-sm":"mini"===this.options.size?"btn-xs":"",c=a('<label class="btn">').html(this.options.on).addClass(this._onstyle+" "+b),d=a('<label class="btn">').html(this.options.off).addClass(this._offstyle+" "+b+" active"),e=a('<span class="toggle-handle btn btn-default">').addClass(b),f=a('<div class="toggle-group">').append(c,d,e),g=a('<div class="toggle btn" data-toggle="toggle">').addClass(this.$element.prop("checked")?this._onstyle:this._offstyle+" off").addClass(b).addClass(this.options.style);this.$element.wrap(g),a.extend(this,{$toggle:this.$element.parent(),$toggleOn:c,$toggleOff:d,$toggleGroup:f}),this.$toggle.append(f);var h=this.options.width||Math.max(c.outerWidth(),d.outerWidth())+e.outerWidth()/2,i=this.options.height||Math.max(c.outerHeight(),d.outerHeight());c.addClass("toggle-on"),d.addClass("toggle-off"),this.$toggle.css({width:h,height:i}),this.options.height&&(c.css("line-height",c.height()+"px"),d.css("line-height",d.height()+"px")),this.update(!0),this.trigger(!0)},c.prototype.toggle=function(){this.$element.prop("checked")?this.off():this.on()},c.prototype.on=function(a){return this.$element.prop("disabled")?!1:(this.$toggle.removeClass(this._offstyle+" off").addClass(this._onstyle),this.$element.prop("checked",!0),void(a||this.trigger()))},c.prototype.off=function(a){return this.$element.prop("disabled")?!1:(this.$toggle.removeClass(this._onstyle).addClass(this._offstyle+" off"),this.$element.prop("checked",!1),void(a||this.trigger()))},c.prototype.enable=function(){this.$toggle.removeAttr("disabled"),this.$element.prop("disabled",!1)},c.prototype.disable=function(){this.$toggle.attr("disabled","disabled"),this.$element.prop("disabled",!0)},c.prototype.update=function(a){this.$element.prop("disabled")?this.disable():this.enable(),this.$element.prop("checked")?this.on(a):this.off(a)},c.prototype.trigger=function(b){this.$element.off("change.bs.toggle"),b||this.$element.change(),this.$element.on("change.bs.toggle",a.proxy(function(){this.update()},this))},c.prototype.destroy=function(){this.$element.off("change.bs.toggle"),this.$toggleGroup.remove(),this.$element.removeData("bs.toggle"),this.$element.unwrap()};var d=a.fn.bootstrapToggle;a.fn.bootstrapToggle=b,a.fn.bootstrapToggle.Constructor=c,a.fn.toggle.noConflict=function(){return a.fn.bootstrapToggle=d,this},a(function(){a("input[type=checkbox][data-toggle^=toggle]").bootstrapToggle()}),a(document).on("click.bs.toggle","div[data-toggle^=toggle]",function(b){var c=a(this).find("input[type=checkbox]");c.bootstrapToggle("toggle"),b.preventDefault()})}(jQuery);

/*
 * bootstrap-filestyle
 * doc: http://markusslima.github.io/bootstrap-filestyle/
 * github: https://github.com/markusslima/bootstrap-filestyle
 *
 * Copyright (c) 2017 Markus Vinicius da Silva Lima
 * Version 2.1.0
 * Licensed under the MIT license.
 */
!function(e){"use strict";var t=0,i=function(t,i){this.options=i,this.$elementFilestyle=[],this.$element=e(t)};i.prototype={clear:function(){this.$element.val(""),this.$elementFilestyle.find(":text").val(""),this.$elementFilestyle.find(".badge").remove()},destroy:function(){this.$element.removeAttr("style").removeData("filestyle"),this.$elementFilestyle.remove()},disabled:function(e){return e!==!0&&e!==!1?this.options.disabled:(this.options.disabled=e,this.$element.prop("disabled",this.options.disabled),this.$elementFilestyle.find("label").prop("disabled",this.options.disabled),this.options.disabled?this.$elementFilestyle.find("label").css("opacity","0.65"):this.$elementFilestyle.find("label").css("opacity","1"),void 0)},dragdrop:function(e){return e!==!0&&e!==!1?this.options.dragdrop:void(this.options.dragdrop=e)},buttonBefore:function(e){if(e===!0)this.options.buttonBefore||(this.options.buttonBefore=e,this.options.input&&(this.$elementFilestyle.remove(),this.constructor(),this.pushNameFiles()));else{if(e!==!1)return this.options.buttonBefore;this.options.buttonBefore&&(this.options.buttonBefore=e,this.options.input&&(this.$elementFilestyle.remove(),this.constructor(),this.pushNameFiles()))}},input:function(e){if(e===!0)this.options.input||(this.options.input=e,this.options.buttonBefore?this.$elementFilestyle.append(this.htmlInput()):this.$elementFilestyle.prepend(this.htmlInput()),this.pushNameFiles(),this.$elementFilestyle.find(".group-span-filestyle").addClass("input-group-btn"));else{if(e!==!1)return this.options.input;this.options.input&&(this.options.input=e,this.$elementFilestyle.find(":text").remove(),this.$elementFilestyle.find(".group-span-filestyle").removeClass("input-group-btn"))}},size:function(e){if(void 0===e)return this.options.size;this.options.size=e;var t=this.$elementFilestyle.find("label"),i=this.$elementFilestyle.find("input");t.removeClass("btn-lg btn-sm"),i.removeClass("form-control-lg form-control-sm"),"nr"!=this.options.size&&(t.addClass("btn-"+this.options.size),i.addClass("form-control-"+this.options.size))},placeholder:function(e){return void 0===e?this.options.placeholder:(this.options.placeholder=e,void this.$elementFilestyle.find("input").attr("placeholder",e))},text:function(e){return void 0===e?this.options.text:(this.options.text=e,void this.$elementFilestyle.find("label .text").html(this.options.text))},btnClass:function(e){return void 0===e?this.options.btnClass:(this.options.btnClass=e,void this.$elementFilestyle.find("label").attr({"class":"btn "+this.options.btnClass+" btn-"+this.options.size}))},badge:function(e){if(e===!0){this.options.badge=e;var t=this.pushNameFiles();this.$elementFilestyle.find("label").append(' <span class="badge '+this.options.badgeName+'">'+t.length+"</span>")}else{if(e!==!1)return this.options.badge;this.options.badge=e,this.$elementFilestyle.find(".badge").remove()}},badgeName:function(e){return void 0===e?this.options.badgeName:(this.options.badgeName=e,void this.$elementFilestyle.find(".badge").attr({"class":"badge "+this.options.badgeName}))},htmlIcon:function(e){return void 0!==e&&(this.options.htmlIcon=e),this.options.htmlIcon},htmlInput:function(){return this.options.input?'<input type="text" class="form-control '+("nr"==this.options.size?"":"form-control-"+this.options.size)+'" placeholder="'+this.options.placeholder+'" disabled> ':""},pushNameFiles:function(){var e="",t=[];void 0===this.$element[0].files?t[0]={name:this.$element[0]&&this.$element[0].value}:t=this.$element[0].files;for(var i=0;i<t.length;i++)e+=t[i].name.split("\\").pop()+", ";return""!==e?this.$elementFilestyle.find(":text").val(e.replace(/\, $/g,"")):this.$elementFilestyle.find(":text").val(""),t},constructor:function(){var i=this,n="",s=i.$element.attr("id"),l="";""!==s&&s||(s="filestyle-"+t,i.$element.attr({id:s}),t++),l='<span class="group-span-filestyle '+(i.options.input?"input-group-btn":"")+'"><label for="'+s+'" style="margin-bottom: 0;" class="btn '+i.options.btnClass+" "+("nr"==i.options.size?"":"btn-"+i.options.size)+'" '+(i.options.disabled||i.$element.attr("disabled")?' disabled="true"':"")+">"+i.htmlIcon()+'<span class="buttonText">'+i.options.text+"</span></label></span>",n=i.options.buttonBefore?l+i.htmlInput():i.htmlInput()+l,i.$elementFilestyle=e('<div class="bootstrap-filestyle input-group"><div name="filedrag"></div>'+n+"</div>"),i.$elementFilestyle.find(".group-span-filestyle").attr("tabindex","0").keypress(function(e){return 13===e.keyCode||32===e.charCode?(i.$elementFilestyle.find("label").click(),!1):void 0}),i.$element.css({position:"absolute",clip:"rect(0px 0px 0px 0px)"}).attr("tabindex","-1").after(i.$elementFilestyle),i.$elementFilestyle.find(i.options.buttonBefore?"label":":input").css({"border-top-left-radius":".25rem","border-bottom-left-radius":".25rem"}),i.$elementFilestyle.find('[name="filedrag"]').css({position:"absolute",width:"100%",height:i.$elementFilestyle.height()+"px","z-index":-1}),(i.options.disabled||i.$element.attr("disabled"))&&(i.$element.attr("disabled","true"),i.options.disabled?i.$elementFilestyle.find("label").css("opacity","0.65"):i.$elementFilestyle.find("label").css("opacity","1")),i.$element.change(function(){var e=i.pushNameFiles();i.options.badge?0==i.$elementFilestyle.find(".badge").length?i.$elementFilestyle.find("label").append(' <span class="badge '+i.options.badgeName+'">'+e.length+"</span>"):0==e.length?i.$elementFilestyle.find(".badge").remove():i.$elementFilestyle.find(".badge").html(e.length):i.$elementFilestyle.find(".badge").remove(),i.options.onChange(e)}),window.navigator.userAgent.search(/firefox/i)>-1&&i.$elementFilestyle.find("label").click(function(){return i.$element.click(),!1}),e(document).on("dragover",function(t){t.preventDefault(),t.stopPropagation(),i.options.dragdrop&&e('[name="filedrag"]').css("z-index","9")}).on("drop",function(t){t.preventDefault(),t.stopPropagation(),i.options.dragdrop&&e('[name="filedrag"]').css("z-index","-1")}),i.$elementFilestyle.find('[name="filedrag"]').on("dragover",function(e){e.preventDefault(),e.stopPropagation()}).on("dragenter",function(e){e.preventDefault(),e.stopPropagation()}).on("drop",function(t){if(t.originalEvent.dataTransfer&&!i.options.disabled&&i.options.dragdrop&&t.originalEvent.dataTransfer.files.length){t.preventDefault(),t.stopPropagation(),i.$element[0].files=t.originalEvent.dataTransfer.files;var n=i.pushNameFiles();i.options.badge?0==i.$elementFilestyle.find(".badge").length?i.$elementFilestyle.find("label").append(' <span class="badge '+i.options.badgeName+'">'+n.length+"</span>"):0==n.length?i.$elementFilestyle.find(".badge").remove():i.$elementFilestyle.find(".badge").html(n.length):i.$elementFilestyle.find(".badge").remove(),e('[name="filedrag"]').css("z-index","-1")}})}};var n=e.fn.filestyle;e.fn.filestyle=function(t,n){var s="",l=this.each(function(){if("file"===e(this).attr("type")){var l=e(this),o=l.data("filestyle"),a=e.extend({},e.fn.filestyle.defaults,t,"object"==typeof t&&t);o||(l.data("filestyle",o=new i(this,a)),o.constructor()),"string"==typeof t&&(s=o[t](n))}});return void 0!==typeof s?s:l},e.fn.filestyle.defaults={text:"Seleccione Archivo",htmlIcon:"",btnClass:"btn-secondary",size:"nr",input:!0,badge:!1,badgeName:"badge-light",buttonBefore:!1,dragdrop:!0,disabled:!1,placeholder:"",onChange:function(){}},e.fn.filestyle.noConflict=function(){return e.fn.filestyle=n,this},e(function(){e(".filestyle").each(function(){var t=e(this),i={input:"false"!==t.attr("data-input"),htmlIcon:t.attr("data-icon"),buttonBefore:"true"===t.attr("data-buttonBefore"),disabled:"true"===t.attr("data-disabled"),size:t.attr("data-size"),text:t.attr("data-text"),btnClass:t.attr("data-btnClass"),badge:"true"===t.attr("data-badge"),dragdrop:"false"!==t.attr("data-dragdrop"),badgeName:t.attr("data-badgeName"),placeholder:t.attr("data-placeholder")};t.filestyle(i)})})}(window.jQuery);
