//~ Empresa Libre
//~ Copyright (C) 2016-2021  Mauricio Baeza Servin (public@correolibre.net)
//~
//~ This program is free software: you can redistribute it and/or modify
//~ it under the terms of the GNU General Public License as published by
//~ the Free Software Foundation, either version 3 of the License, or
//~ (at your option) any later version.
//~
//~ This program is distributed in the hope that it will be useful,
//~ but WITHOUT ANY WARRANTY; without even the implied warranty of
//~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//~ GNU General Public License for more details.
//~
//~ You should have received a copy of the GNU General Public License
//~ along with this program.  If not, see <http://www.gnu.org/licenses/>.


var form_editar_usuario_elementos = [
    {view: "text", id: 'txt_usuarioe_usuario', label: "Usuario",
        name: "usuario", labelPosition: 'top', required: true},
    {view: "text", id: 'txt_usuarioe_nombre', label: "Nombre", name: "nombre",
        labelPosition: 'top', required: true},
    {view: "text", id: 'txt_usuarioe_apellidos', label: "Apellidos",
        name: "apellidos", labelPosition: 'top'},
    {view: "text", id: 'txt_usuarioe_correo', label: "Correo", name: "correo",
        labelPosition: 'top'},
    {view: 'text', id: 'txt_usuarioe_contra1', name: 'contra1',
        label: 'Contraseña: ', type: 'password',
        labelPosition: 'top'},
    {view: 'text', id: 'txt_usuarioe_contra2', name: 'contra2',
        label: 'Confirmación de contraseña: ',
        type: 'password', labelPosition: 'top'},
    {cols:[
        {view: "button", value: "Cancelar", click:function(){
            this.getTopParentView().hide();
        }},
        {view: "button", type:"form", value: "Guardar",
            click:function(){
                update_grid_usuarios(this.getFormView(), this.getTopParentView())
            }
        }
    ]}
]


var admin_ui_windows = {
    init: function(){
        webix.ui({
            view: 'window',
            id: 'win_edit_usuario',
            head: 'Editar Usuario',
            modal: true,
            position: 'center',
            body: {
                view: 'form', id: 'form_editar_usuario',
                elements: form_editar_usuario_elementos
            }
        })

        $$('form_editar_usuario').bind($$('grid_usuarios'))

    },
}


var grid_cols_niveles_educativos = [
    {id: 'id', header: 'ID', hidden: true},
    {id: 'delete', header: '', width: 30, css: 'delete'},
    {id: 'nombre', header: 'Nivel', fillspace: 1},
    {id: 'autorizacion', header: 'Autorización', fillspace: 1},
]


var grid_niveles_educativos = {
    view: 'datatable',
    id: 'grid_niveles_educativos',
    select: 'cell',
    adjust: true,
    autoheight: true,
    headermenu: true,
    columns: grid_cols_niveles_educativos,
    on:{
        'data->onStoreUpdated':function(){
            this.data.each(function(obj, i){
                obj.delete = '-'
            })
        }
    },
}


var form_controls_niveles_educativos = [
    {cols: [
        {view: 'text', id: 'txt_nivel_educativo', label: 'Nivel', suggest: '/values/nivedusat',
            labelPosition: 'top', name: 'nombre', required: true},
        {view: "text", id: 'txt_auth_rvoe', label: 'Autorización',
            name: 'autorizacion', labelPosition: 'top'},
        {view: 'button', type: 'iconTop', icon: 'plus', label: 'Agregar',
            autowidth: true, click: function(){
                add_nivel_educativo_click()
            }}
    ]},
    grid_niveles_educativos,
    {},
    {cols:[{},
        {view: "button", value: 'Cerrar', click: "$$('win_niveles_educativos').close()"},
    {}]}
]


var admin_ui_niveles_educativos = {
    init: function(){
        webix.ui({
            view: 'window',
            id: 'win_niveles_educativos',
            head: 'Niveles Educativos',
            width: 500,
            modal: true,
            position: 'center',
            body: {
                view: 'form', id: 'form_niveles_educativos',
                elements: form_controls_niveles_educativos
            }
        })

        $$('grid_niveles_educativos').attachEvent('onItemClick', grid_niveles_educativos_click)

    },
}


var menu_data = [
    {id: 'app_admin_home', icon: 'dashboard', value: 'Inicio'},
    {id: 'app_emisor', icon: 'user-circle', value: 'Emisor'},
    {id: 'app_folios', icon: 'sort-numeric-asc', value: 'Folios'},
    {id: 'app_correo', icon: 'envelope-o', value: 'Correo'},
    {id: 'app_sat', icon: 'table', value: 'Catalogos SAT'},
    {id: 'app_usuarios', icon: 'users', value: 'Usuarios'},
    {id: 'app_options', icon: 'check-circle-o', value: 'Opciones'},
    {id: 'app_utilidades', icon: 'cog', value: 'Utilidades'},
]


var sidebar_admin = {
    view: 'sidebar',
    id: 'sidebar_admin',
    data: menu_data,
    ready: function(){
        this.select('app_admin_home');
        this.open(this.getParentId('app_admin_home'));
    },
    on:{
        onAfterSelect: function(id){
            $$('multi_admin').setValue(id)
        }
    },
}


var emisor_datos_fiscales = [
    {template: 'Datos SAT', type: 'section'},
    {cols: [
        {view: 'text', id: 'emisor_rfc', name: 'emisor_rfc', label: 'RFC: ',
            width: 300, required: true, invalidMessage: 'RFC inválido',
            readonly: true, attributes: {maxlength: 13}},
        {view: 'text', id: 'emisor_curp', name: 'emisor_curp', label: 'CURP: ',
            width: 350, labelWidth: 100, attributes: {maxlength: 18},
            placeholder: 'Solo si timbran nómina'},
        {}]},
    {view: 'text', id: 'emisor_nombre', name: 'emisor_nombre',
        label: 'Razón Social: ', required: true,
        invalidMessage: 'La Razón Social es requerida'},
    {cols: [
        {view: 'search', id: 'emisor_cp', name: 'emisor_cp', width: 300,
            label: 'C.P.: ', required: true, attributes: {maxlength: 5},
            invalidMessage: 'El C.P. es requerido'},
        {view: 'text', id: 'emisor_cp2', name: 'emisor_cp2', width: 300,
            label: 'C.P. de Expedición: ', attributes: {maxlength: 5}},
        {view: 'counter', id: 'emisor_hours', name: 'emisor_hours', value: 0,
            required: false, label: 'Horas Dif.: ', step: 1, min: -1, max: 3}
        ]},
    {cols: [
        {view: 'label', label: 'Regimenes Fiscales *', required: true}, {}]},
    {cols: [{view: 'list', id: 'lst_emisor_regimen', select: 'multiselect',
        name: 'lst_emisor_regimen', width: 600, height: 125, required: true,
        data: []}, {}]},
    {template: 'Dirección Fiscal', type: 'section'},
    {view: 'text', id: 'emisor_calle', name: 'emisor_calle', label: 'Calle: '},
    {cols: [{view: 'text', id: 'emisor_no_exterior', name: 'emisor_no_exterior',
        width: 300, label: 'No Exterior: '},{}]},
    {cols: [{view: 'text', id: 'emisor_no_interior', name: 'emisor_no_interior',
        width: 300, label: 'No Interior: '},{}]},
    {view: 'text', id: 'emisor_colonia', name: 'emisor_colonia',
        label: 'Colonia: '},
    {view: 'text', id: 'emisor_municipio', name: 'emisor_municipio',
        label: 'Municipio: '},
    {view: 'text', id: 'emisor_estado', name: 'emisor_estado',
        label: 'Estado: '},
    {view: 'text', id: 'emisor_pais', name: 'emisor_pais', label: 'País: ',
        value: 'México', readonly: true},
    {template: '', type: 'section', minHeight: 25},
]


var emisor_otros_datos= [
    {template: 'Generales', type: 'section'},
    {cols: [
        {view: 'search', id: 'emisor_logo', icon: 'file-image-o',
            name: 'emisor_logo', label: 'Logotipo: ', placeholder: 'Solo formato PNG'},
        {view: 'text', id: 'emisor_nombre_comercial',
            name: 'emisor_nombre_comercial', label: 'Nombre comercial: '},
        ]},
    {cols: [
        {view: 'text', id: 'emisor_telefono', name: 'emisor_telefono',
            label: 'Teléfonos: '},
        {view: 'text', id: 'emisor_correo', name: 'emisor_correo',
            label: 'Correos: '},
        ]},
    {cols: [
        {view: 'text', id: 'emisor_registro_patronal', attributes: {maxlength: 20},
            name: 'emisor_registro_patronal', label: 'Registro Patronal: ',
            placeholder: 'Solo para timbrado de nómina'},
        {view: 'text', id: 'emisor_web', name: 'emisor_web',
            label: 'Página Web: '},
        ]},
    {template: 'Escuela', type: 'section'},
    {cols: [{view: 'checkbox', id: 'chk_escuela', name: 'es_escuela',
        label: 'Es Escuela'},
        {view: 'button', id: 'cmd_niveles_educativos', label: 'Niveles Educativos',
            type: 'form', align: 'center', autowidth: true, disabled: true},
            {}, {}]},
    {template: 'ONG', type: 'section'},
    {view: 'checkbox', id: 'chk_ong', name: 'es_ong', label: 'Es ONG'},
    {cols: [{view: 'text', id: 'ong_autorizacion', name: 'ong_autorizacion',
        label: 'Autorización: ', disabled: true,
        placeholder: 'Número de autorización del SAT'}, {}]},
    {cols: [{view: 'datepicker', id: 'ong_fecha', name: 'ong_fecha',
        label: 'Fecha de Autorización: ', disabled: true, format: '%d-%M-%Y',
        placeholder: 'Fecha de autorización en el SAT'}, {}]},
    {cols: [{view: 'datepicker', id: 'ong_fecha_dof', name: 'ong_fecha_dof',
        label: 'Fecha de DOF: ', disabled: true, format: '%d-%M-%Y',
        placeholder: 'Fecha de publicación en el DOF'}, {}]},
    {template: 'Soporte', type: 'section'},
    //~ {view: 'text', id: 'correo_timbrado',
        //~ name: 'correo_timbrado', label: 'Usuario para Timbrado: '},
    //~ {view: 'text', id: 'token_timbrado',
        //~ name: 'token_timbrado', label: 'Token de Timbrado: '},
    {view: 'text', id: 'token_soporte',
        name: 'token_soporte', label: 'Token de Soporte: '},
]


var col_sello = {rows: [
    {template: 'Certificado actual', type: 'section'},
    {view: 'form', id: 'form_cert', rows: [
    {cols: [{view: 'text', id: 'cert_rfc', name: 'cert_rfc',
        label: 'RFC: ', readonly: true, placeholder: 'Ninguno'}]},
    {cols: [{view: 'text', id: 'cert_serie', name: 'cert_serie',
        label: 'Serie: ', readonly: true, placeholder: 'Ninguno'}]},
    {cols: [{view: 'text', id: 'cert_desde', name: 'cert_desde',
        label: 'Vigente desde: ', readonly: true}]},
    {cols: [{view: 'text', id: 'cert_hasta', name: 'cert_hasta',
        label: 'Vigente hasta: ', readonly: true}]},
    ]}
]}


var col_fiel = {rows: [
    {template: 'Fiel actual', type: 'section'},
    {view: 'form', id: 'form_fiel', rows: [
    {cols: [{view: 'text', id: 'fiel_rfc', name: 'fiel_rfc',
        label: 'RFC: ', readonly: true, placeholder: 'Ninguno'}]},
    {cols: [{view: 'text', id: 'fiel_serie', name: 'fiel_serie',
        label: 'Serie: ', readonly: true, placeholder: 'Ninguno'}]},
    {cols: [{view: 'text', id: 'fiel_desde', name: 'fiel_desde',
        label: 'Vigente desde: ', readonly: true}]},
    {cols: [{view: 'text', id: 'fiel_hasta', name: 'fiel_hasta',
        label: 'Vigente hasta: ', readonly: true}]},
    ]}
]}


            //~ {view: 'uploader', id: 'up_cert', autosend: false, link: 'lst_cert',
                //~ value: 'Seleccionar certificado', upload: '/values/files'}, {}]},

var emisor_certificado = [
    {cols: [col_sello, col_fiel]},
    {template: 'Cargar Certificado', type: 'section'},
    {view: 'form', id: 'form_upload', rows: [
        {cols: [{},
            {view: 'uploader', id: 'up_cert', autosend: false, link: 'lst_cert',
                value: 'Seleccionar certificado (CER y KEY)'}, {}]},
        {cols: [{},
            {view: 'list',  id: 'lst_cert', name: 'certificado',
                type: 'uploader', autoheight:true, borderless: true}, {}]},
        {cols: [{},
            {view: 'text',  id: 'txt_contra', name: 'contra',
                label: 'Contraseña KEY', labelPosition: 'top',
                labelAlign: 'center', type: 'password', required: true}, {}]},
        {cols: [{}, {view: 'button', id: 'cmd_subir_certificado',
            label: 'Subir certificado'}, {}]},
    ]},
]


var grid_emisor_cuentas_banco_cols = [
    {id: 'id', header: 'ID', hidden: true},
    {id: 'activa', header: 'Activa', template: '{common.checkbox()}',
        editor: 'checkbox', width: 50},
    {id: 'nombre', header: 'Nombre', fillspace: 1},
    {id: 'banco', header: 'Banco', fillspace: 1},
    {id: 'fecha_apertura', header: 'Fecha de Apertura', fillspace: 1},
    {id: 'cuenta', header: 'Cuenta', fillspace: 1},
    {id: 'clabe', header: 'CLABE', fillspace: 1},
    {id: 'moneda', header: 'Moneda', fillspace: 1},
    {id: 'saldo', header: 'Saldo', width: 150, format: webix.i18n.priceFormat,
        css: 'right'},
]


var grid_emisor_cuentas_banco = {
    view: 'datatable',
    id: 'grid_emisor_cuentas_banco',
    select: 'row',
    adjust: true,
    autoheight: true,
    headermenu: true,
    columns: grid_emisor_cuentas_banco_cols,
}


var emisor_cuentas_banco = [
    {template: 'Agregar cuenta de banco', type: 'section'},
    {view: 'form', id: 'form_emisor_cuenta_banco', rows: [
    {cols: [
        {view: 'text', id: 'emisor_cuenta_nombre', name: 'emisor_cuenta_nombre',
            label: 'Nombre: ', required: true},
        {view: 'richselect', id: 'lst_emisor_banco', name: 'emisor_banco',
            label: 'Banco: ', required: true, options: []},
        ]},
    {cols: [
        {view: 'text', id: 'emisor_cuenta', name: 'emisor_cuenta',
            label: 'Cuenta: ', required: true},
        {view: 'text', id: 'emisor_clabe', name: 'emisor_clabe',
            label: 'CLABE: ', required: true},
        ]},
    {cols: [
        {view: 'richselect', id: 'lst_emisor_cuenta_moneda',
            name: 'emisor_cuenta_moneda', label: 'Moneda: ', required: true,
            options: []},
        {view: 'currency', type: 'text', id: 'emisor_cuenta_saldo_inicial',
            name: 'emisor_cuenta_saldo_inicial', label: 'Saldo inicial: ',
            required: true, invalidMessage: 'Captura un valor númerico',
            inputAlign: 'right', value: ''},
        ]},
    {cols: [
        {view: 'datepicker', id: 'emisor_cuenta_fecha', format: '%d-%M-%Y',
            name: 'emisor_cuenta_fecha', label: 'Fecha de apertura: ',
            required: true},
        {view: 'datepicker', id: 'emisor_fecha_saldo', format: '%d-%M-%Y',
            name: 'emisor_fecha_saldo', label: 'Fecha saldo inicial: ',
            required: true},
        ]},
    {minHeight: 10},
    {cols: [{},
        {view: 'button', id: 'cmd_emisor_agregar_cuenta',
            label: 'Agregar cuenta'}, {},
        {view: 'button', id: 'cmd_emisor_eliminar_cuenta',
            label: 'Eliminar cuenta'},
        {}]},
    ],

    rules: {
        emisor_cuenta_saldo_inicial: function(value){return value.trim() != "$";},
    }

    },
    {minHeight: 20, maxHeight: 20},
    {template: 'Cuentas de banco existentes', type: 'section'},
    grid_emisor_cuentas_banco,
    {minHeight: 50},
]


var controls_emisor = [
    {
        view: 'tabview',
        id: 'tab_emisor',
        tabbar: {options: [
                'Datos Fiscales',
                'Otros Datos',
                'Certificado',
                'Cuentas de Banco']},
        animate: true,
        cells: [
            {id: 'Datos Fiscales', rows: emisor_datos_fiscales},
            {id: 'Otros Datos', rows: emisor_otros_datos},
            {id: 'Certificado', rows: emisor_certificado},
            {id: 'Cuentas de Banco', rows: emisor_cuentas_banco},
        ]
    }
]


var form_emisor = {
    type: 'space',
    responsive: true,
    cols: [{
        view: 'form',
        id: 'form_emisor',
        complexData: true,
        scroll: true,
        elements: controls_emisor,
        elementsConfig: {
            labelWidth: 150,
            labelAlign: 'right'
        },
        rules: {
            emisor_nombre: function(value){return value.trim() != ''},
        }
    }],
}


var options_usarcon = [
    {id: 'S', value: 'Todos'},
    {id: 'I', value: 'Ingreso'},
    {id: 'E', value: 'Egreso'},
    {id: 'T', value: 'Traslado'},
]


var grid_folios_cols = [
    {id: 'delete', header: '', width: 30, css: 'delete'},
    {id: 'serie', header: 'Serie', fillspace: 1},
    {id: 'inicio', header: 'Inicio', fillspace: 1},
    {id: 'usarcon', header: 'Usar Con', fillspace: 1},
    {id: 'pre', header: 'Predeterminado', fillspace: 1}
]


var grid_folios = {
    view: 'datatable',
    id: 'grid_folios',
    select: 'row',
    adjust: true,
    headermenu: true,
    columns: grid_folios_cols,
}


var emisor_folios = [
    {template: 'Nueva serie', type: 'section'},
    {cols: [
        {view: 'text', id: 'folio_serie', name: 'folio_serie', label: 'Serie: ',
            required: true, attributes: {maxlength: 15}},
        {view: 'counter', id: 'folio_inicio', name: 'folio_inicio', value: 1,
            required: true, label: 'Inicio: ', step: 1, min: 1},
        {view: 'richselect', id: 'folio_usarcon', name: 'folio_usarcon',
            label: 'Usar Con: ', value: 'S', required: true,
            options: options_usarcon},
    ]},
    {maxHeight: 20},
    {cols: [{},
        {view: 'button', id: 'cmd_agregar_serie', label: 'Agregar Serie',
            autowidth: true, type: 'form'},
    {}]},
    {template: 'Series guardadas', type: 'section'},
    grid_folios,
    {template: 'Opciones', type: 'section'},
    {view: 'checkbox', id: 'chk_folio_custom', labelWidth: 0,
        labelRight: 'Permitir capturar el folio manualmente (no recomendado): '},
]


var emisor_correo = [
    {template: 'Servidor de Salida', type: 'section'},
    {cols: [
        {view: 'text', id: 'correo_servidor', name: 'correo_servidor',
            label: 'Servidor SMTP: '},
    {}]},
    {cols: [
        {view: 'counter', id: 'correo_puerto', name: 'correo_puerto',
            label: 'Puerto: ', value: 26, step: 1},
    {}]},
    {cols: [
        {view: 'checkbox', id: 'correo_ssl', name: 'correo_ssl',
            label: 'Usar TLS/SSL: ', maxWidth: 210},
        {view: 'checkbox', id: 'correo_starttls', name: 'correo_starttls',
            label: 'Usar STARTTLS: '},
    {}]},
    {cols: [
        {view: 'text', id: 'correo_usuario', name: 'correo_usuario',
            label: 'Usuario: '},
    {}]},
    {cols: [
        {view: 'text', id: 'correo_contra', name: 'correo_contra',
            label: 'Contraseña: ', type: 'password'},
    {}]},
    {cols: [
        {view: 'text', id: 'correo_copia', name: 'correo_copia',
            label: 'Con copia a: ', bottomLabel: 'Uno o más correos electrónicos separados por comas'}
    ]},
    {cols: [
        {view: 'text', id: 'correo_asunto', name: 'correo_asunto',
            label: 'Asunto del correo: ', bottomLabel: 'Puedes usar campos: {serie}{folio}'}
    ]},
    {cols: [
        {view: 'textarea', id: 'correo_mensaje', name: 'correo_mensaje',
            label: 'Mensaje del correo: ', height: 200}
    ]},
    {cols: [
        {view: 'checkbox', id: 'correo_directo', name: 'correo_directo',
            label: 'Enviar directamente: ', bottomLabel: 'Envia la factura directamente al cliente al generarse'},
    {}]},
    {cols: [
        {view: 'checkbox', id: 'correo_confirmacion', name: 'correo_confirmacion',
            label: 'Solicitar confirmación: ', bottomLabel: 'Solicita al cliente la confirmación de recepción'},
    {}]},
    {minHeight: 25},
    {cols: [{},
        {view: 'button', id: 'cmd_probar_correo', label: 'Probar Configuración',
            autowidth: true, type: 'form'},
        {maxWidth: 50},
        {view: 'button', id: 'cmd_guardar_correo', label: 'Guardar Configuración',
            autowidth: true, type: 'form'},
        {maxWidth: 50},
        {view: 'button', id: 'cmd_clean_email', label: 'Borrar Configuración',
            autowidth: true, type: 'form'},
    {}]}
]


var controls_folios = [
    {
        view: 'tabview',
        id: 'tab_folios',
        animate: true,
        cells: [
            {id: 'Folios', rows: emisor_folios},
        ]
    }
]


var controls_correo = [
    {
        view: 'tabview',
        id: 'tab_correo',
        tabbar: {options: ['Correo Electrónico']},
        animate: true,
        cells: [
            {id: 'Correo Electrónico', rows: emisor_correo},
        ]
    }
]


var form_folios = {
    type: 'space',
    cols: [{
        view: 'form',
        id: 'form_folios',
        complexData: true,
        scroll: true,
        elements: controls_folios,
        elementsConfig: {
            labelWidth: 100,
            labelAlign: 'right'
        },
        rules: {
            folio_serie: function(value){return value.trim() != ''},
            folio_inicio: function(value){return value > 0},
        }
    }],
}


var form_correo = {
    type: 'space',
    cols: [{
        view: 'form',
        id: 'form_correo',
        complexData: true,
        scroll: true,
        elements: controls_correo,
        elementsConfig: {
            labelWidth: 150,
            labelAlign: 'right'
        },
    }],
}


var type_make_pdf = [
    {id: 1, value: 'ODS'},
    {id: 2, value: 'JSON'},
]


//~ Templates
var opt_templates_cfdi = [
    {id: '_4.0.ods', value: 'CFDI v4.0'},
    {id: '_4.0_cn_1.2.ods', value: 'CFDI v4.0 - Nómina v1.2'},
    {id: '_4.0_cp_2.0.ods', value: 'CFDI v4.0 - Pagos v2.0'},
    {id: '_4.0_ccp_2.0.ods', value: 'CFDI v4.0 - Carta Porte v2.0'},
    {id: '_4.0_ccp_3.0.ods', value: 'CFDI v4.0 - Carta Porte v3.0'},
    {id: '_4.0_cd_1.1.ods', value: 'CFDI v4.0 - Donativos v1.1'},
    {id: '_4.0_cce_2.0.ods', value: 'CFDI v4.0 - Comercio Exterior v2.0'},
    {id: '_4.0.json', value: 'CFDI v4.0 - JSON'},
    {id: '_3.3.ods', value: 'CFDI v3.3'},
    {id: '_3.3_cn_1.2.ods', value: 'CFDI v3.3 - Nómina v1.2'},
    {id: '_3.3_ccp_2.0.ods', value: 'CFDI v3.3 - Carta Porte v2.0'},
    {id: '_3.3_cp_1.0.ods', value: 'CFDI v3.3 - Pagos v1.0'},
    {id: '_3.3.json', value: 'CFDI v3.3 - JSON'},
    {id: '_3.2.ods', value: 'CFDI v3.2'}
]


var options_templates = [
    {maxHeight: 25},
    {cols: [{maxWidth: 20},
        {view: 'richselect', id: 'lst_templates_cfdi', label: 'Plantillas CFDI: ', labelWidth: 100, options: opt_templates_cfdi},
        {maxWidth: 10},
        {view: 'button', id: 'cmd_template_upload', type: 'iconButton', icon: 'file', width: 35},
        {},
        {maxWidth: 20} ]},
    {maxHeight: 50},
    {cols: [{maxWidth: 20},
        {view: 'search', id: 'txt_plantilla_factura_html', name: 'plantilla_factura_html',
            label: 'Plantilla Factura v3.3 (HTML): ', labelPosition: 'top',
            icon: 'file'}, {maxWidth: 25},
        {view: 'search', id: 'txt_plantilla_factura_css', name: 'plantilla_factura_css',
            label: 'Archivo de estilos (CSS): ', labelPosition: 'top',
            icon: 'file'}, {maxWidth: 20} ]},
    {maxHeight: 20},
    {cols: [{maxWidth: 20},
        {view: 'search', id: 'txt_plantilla_ticket', name: 'plantilla_ticket',
            label: 'Plantilla para Tickets (ODS): ', labelPosition: 'top',
            icon: 'file'},
        {}]},
    {maxHeight: 20},
    {cols: [{maxWidth: 20},
        {view: 'radio', id: 'make_pdf_from', name: 'make_pdf_from', labelWidth: 150,
            label: 'Generar PDF desde: ', value: 1, options: type_make_pdf},
        {}]},
{}]


var options_pac = [
    {id: 'finkok', value: 'Finkok'},
    {id: 'comercio', value: 'Comercio Digital'},
]


var options_admin_otros = [
    {maxHeight: 15},
    {template: 'Facturación', type: 'section'},
    {cols: [{maxWidth: 15},
        {view: 'checkbox', id: 'chk_config_ocultar_metodo_pago', labelWidth: 0,
            labelRight: 'Ocultar método de pago'},
        {view: 'checkbox', id: 'chk_config_ocultar_condiciones_pago', labelWidth: 0,
            labelRight: 'Ocultar condiciones de pago'},
        {view: 'checkbox', id: 'chk_config_send_zip', labelWidth: 0,
            labelRight: 'Enviar factura en ZIP'},
        {view: 'checkbox', id: 'chk_config_open_pdf', labelWidth: 0,
            labelRight: 'Abrir PDF al timbrar'},
        {view: 'checkbox', id: 'chk_config_show_pedimento', labelWidth: 0,
            labelRight: 'Mostrar Pedimento'},
        ]},
    {cols: [{maxWidth: 15},
        {view: 'checkbox', id: 'chk_config_tax_locales', labelWidth: 0,
            labelRight: 'Impuestos locales, calcular antes del descuento'},
        {view: 'checkbox', id: 'chk_config_tax_decimals', labelWidth: 0,
            labelRight: 'Calcular impuestos con 4 decimales', hidden: true},
        {view: 'checkbox', id: 'chk_config_price_with_taxes_in_invoice', labelWidth: 0,
            labelRight: 'Precio incluye impuestos'},
        {view: 'checkbox', id: 'chk_config_add_same_product', labelWidth: 0,
            labelRight: 'Permitir agregar el mismo producto'},
        ]},
    {cols: [{maxWidth: 15},
        {view: 'checkbox', id: 'chk_config_tax_locales_truncate', labelWidth: 0,
            labelRight: 'Impuestos locales, truncar valores'},
        {view: 'checkbox', id: 'chk_config_decimales_precios', labelWidth: 0,
            labelRight: 'Precios con 4 decimales'},
        {view: 'checkbox', id: 'chk_config_user_show_doc', labelWidth: 0,
            labelRight: 'Usuarios pueden ver todos los documentos'},
        ]},
    {cols: [{maxWidth: 15},
        {view: 'checkbox', id: 'chk_config_invoice_by_ticket', labelWidth: 0,
            labelRight: 'Factura global por ticket'},
        {view: 'checkbox', id: 'chk_config_show_total_cant', labelWidth: 0,
            labelRight: 'Mostrar total de cantidades'},
        {view: 'checkbox', id: 'chk_config_show_filter_by_day', labelWidth: 0,
            labelRight: 'Mostrar filtro por día'},
        {}
        ]},
    {cols: [{maxWidth: 15},
        {view: 'checkbox', id: 'chk_cancel_invoices_by_admin', labelWidth: 0,
            labelRight: 'Solo admins pueden cancelar'},
        {}
        ]},
    {cols: [{maxWidth: 15},
        {view: 'checkbox', id: 'chk_config_change_date_invoice', labelWidth: 0,
            labelRight: 'Permitir cambiar fecha al facturar [No recomendable]'},
        {}
        ]},
    {maxHeight: 15},

    {template: 'Timbrado', type: 'section'},
    {cols: [{maxWidth: 15},
        {view: 'richselect', id: 'lst_pac', name: 'lst_pac', width: 300,
            label: 'PAC: ', value: '', required: true,
            labelAlign: 'right', options: options_pac}, {view: 'label',
            label: ' NO cambies este valor, a menos que se te haya indicado'},
        ]},
    {cols: [{maxWidth: 15},
        {view: 'text', id: 'user_timbrado', name: 'user_timbrado',
            label: 'Usuario: ', labelAlign: 'right', required: true},
        {view: 'text', id: 'token_timbrado', name: 'token_timbrado',
            label: 'Token: ', labelAlign: 'right', required: true},
        ]},
    {cols: [{maxWidth: 15}, {},
        {view: 'button', id: 'cmd_save_pac', label: 'Guardar',
            autowidth: true, type: 'form'}, {},
        ]},
    {maxHeight: 20},

    {template: 'Ayudas varias', type: 'section'},
    {cols: [{maxWidth: 15},
        {view: 'checkbox', id: 'chk_config_anticipo', labelWidth: 0,
            labelRight: 'Ayuda para generar anticipos'},
        {}]},
    {maxHeight: 20},
    {template: 'Punto de venta', type: 'section'},
    {cols: [{maxWidth: 15},
        {view: 'checkbox', id: 'chk_usar_punto_de_venta', labelWidth: 0,
            labelRight: 'Usar punto de venta'},
        {view: 'checkbox', id: 'chk_ticket_pdf_show', labelWidth: 0,
            labelRight: 'Abrir PDF al generar'},
        {view: 'checkbox', id: 'chk_ticket_direct_print', labelWidth: 0,
            labelRight: 'Imprimir al generar'},
        {view: 'text', id: 'txt_ticket_printer', name: 'ticket_printer',
            label: 'Impresora: ', labelWidth: 75, labelAlign: 'right',
            placeholder: 'ENTER para guardar'},
        {maxWidth: 15}]},
    {cols: [{maxWidth: 15},
        {view: 'checkbox', id: 'chk_ticket_edit_cant', labelWidth: 0,
            labelRight: 'Solicitar cantidad al agregar'},
        {view: 'checkbox', id: 'chk_ticket_total_up', labelWidth: 0,
            labelRight: 'Mostrar total arriba'},
        {view: 'checkbox', id: 'chk_ticket_user_show_doc', labelWidth: 0,
            labelRight: 'Usuarios pueden ver todos los documentos'}
        ]},
    {cols: [{maxWidth: 15},
        {view: 'checkbox', id: 'chk_cancel_tickets_by_admin', labelWidth: 0,
            labelRight: 'Solo admins pueden cancelar'},
        {}
        ]},
    {maxHeight: 20},
{}]


var options_admin_partners = [
    {maxHeight: 20},
    {cols: [{maxWidth: 15},
        {view: 'checkbox', id: 'chk_config_change_balance_partner',
            labelWidth: 0, labelRight: 'Permitir cambiar saldo'},
        ]},
]


var grid_warehouse_cols = [
    {id: 'id', header: 'ID', hidden: true},
    {id: 'delete', header: '', width: 30, css: 'delete'},
    {id: 'name', header: 'Nombre', fillspace: 1},
]


var grid_warehouse = {
    view: 'datatable',
    id: 'grid_warehouse',
    select: 'row',
    adjust: true,
    headermenu: true,
    footer: true,
    columns: grid_warehouse_cols,
    on:{
        'data->onStoreUpdated':function(){
            this.data.each(function(obj, i){
                obj.delete = '-'
            })
        }
    },
}


var options_admin_products = [
    {maxHeight: 20},
    {cols: [{view: 'checkbox', id: 'chk_config_cuenta_predial', labelWidth: 15,
        labelRight: 'Mostrar cuenta predial'}]},
    {cols: [{view: 'checkbox', id: 'chk_config_codigo_barras', labelWidth: 15,
        labelRight: 'Mostrar código de barras'}]},
    {cols: [{view: 'checkbox', id: 'chk_config_precio_con_impuestos', labelWidth: 15,
        labelRight: 'Mostrar precio con impuestos'}]},
    {cols: [{view: 'checkbox', id: 'chk_llevar_inventario', labelWidth: 15,
        labelRight: 'Mostrar inventario'}]},
    {cols: [{maxWidth: 30}, {view: 'checkbox', id: 'chk_multi_stock', labelWidth: 15,
        labelRight: 'Multialmacen', disabled: true}]},
    {cols: [{maxWidth: 30}, {rows: [
        {template: 'Agregar Almacen', type: 'section', id: 'template_add_warehouse'},
        {cols: [
            {view: 'text', id: 'txt_add_warehouse', label: 'Nombre: ',
                labelPosition: 'left', required: true},
            {view: 'button', id: 'cmd_add_warehouse', label: 'Agregar',
                autowidth: true, type: 'iconButton', icon: 'plus'},
        ]},
        {template: 'Almacenes', type: 'section'},
        grid_warehouse,
        ]}, {},
    ]}

    //~ {cols: [{view: 'checkbox', id: 'chk_use_packing', labelWidth: 15,
        //~ labelRight: 'Usar empaques', hidden: true}]},
]


var options_admin_complements = [
    {maxHeight: 10},
    {template: 'Complemento de Nómina', type: 'section'},
    {cols: [{maxWidth: 15},
        {view: 'checkbox', id: 'chk_usar_nomina', labelWidth: 0,
            labelRight: 'Usar complemento de Nómina'},
        {view: 'text', id: 'txt_config_nomina_serie', name: 'config_nomina_serie',
            label: 'Serie', labelWidth: 50, labelAlign: 'right'},
        {view: 'text', id: 'txt_config_nomina_folio', name: 'config_nomina_folio',
            label: 'Folio', labelWidth: 50, labelAlign: 'right'},
    {maxWidth: 15}]},
    {maxHeight: 10},
    {template: 'Complemento de Pagos', type: 'section'},
    {cols: [{maxWidth: 15},
        {view: 'checkbox', id: 'chk_config_pagos', labelWidth: 0,
            labelRight: 'Usar complemento de pagos'},
        {view: 'checkbox', id: 'chk_cfg_pays_data_bank', labelWidth: 0,
            labelRight: 'Usar datos bancarios'},
        {view: 'text', id: 'txt_config_cfdipay_serie', name: 'txt_config_cfdipay_serie',
            label: 'Serie', labelWidth: 50, labelAlign: 'right'},
        {view: 'text', id: 'txt_config_cfdipay_folio', name: 'txt_config_cfdipay_serie',
            label: 'Folio', labelWidth: 50, labelAlign: 'right'},
    {maxWidth: 15}]},
    {maxHeight: 10},
    {template: 'Complemento de Divisas', type: 'section'},
    {cols: [{maxWidth: 15},
        {view: 'checkbox', id: 'chk_config_divisas', labelWidth: 0,
            labelRight: 'Usar complemento de divisas'},
    {maxWidth: 15}]},
    {maxHeight: 10},
    {template: 'Complemento INE', type: 'section'},
    {cols: [{maxWidth: 15},
        {view: 'checkbox', id: 'chk_config_ine', labelWidth: 0,
            labelRight: 'Usar el complemento INE'},
    {maxWidth: 15}]},
    {maxHeight: 10},
    {template: 'Complemento para escuelas EDU', type: 'section'},
    {cols: [{maxWidth: 15},
        {view: 'checkbox', id: 'chk_config_edu', labelWidth: 0,
            labelRight: 'Usar el complemento EDU'},
    {maxWidth: 15}]},
    {maxHeight: 10},
    {template: 'Complemento Leyendas Fiscales', type: 'section'},
    {cols: [{maxWidth: 15},
        {view: 'checkbox', id: 'chk_config_leyendas_fiscales', labelWidth: 0,
            labelRight: 'Usar el complemento Leyendas Fiscales'},
        {view: 'button', id: 'cmd_admin_leyendas_fiscales', label: 'Leyendas Fiscales',
            type: 'form', align: 'center', autowidth: true, disabled: true},
        {}, {maxWidth: 15}
    ]},
    {maxHeight: 10},
    {template: 'Complemento para Carta Porte', type: 'section'},
    {cols: [{maxWidth: 15},
        {view: 'checkbox', id: 'chk_config_carta_porte', labelWidth: 0,
            labelRight: 'Usar el complemento Carta Porte'},
    {maxWidth: 15}]},
    {template: 'Complemento para Comercio Exterior', type: 'section'},
    {cols: [{maxWidth: 15},
        {view: 'checkbox', id: 'chk_config_comercio_exterior', labelWidth: 0,
            labelRight: 'Usar el complemento Comercio Exterior'},
    {maxWidth: 15}]},
]


var controls_add_sucursal = [{cols: [
    {maxWidth: 20},
    {view: 'text', id: 'txt_sucursal_add_name', name: 'sucursal_add_name',
        label: 'Nombre: ', labelPosition: 'top', required: true},
    {view: 'richselect', id: 'lst_sucursal_add_invoice', name: 'sucursal_add_invoice',
        label: 'Serie Facturas: ', labelPosition: 'top', required: true, options: []},
    {view: 'text', id: 'txt_sucursal_add_ticket', name: 'sucursal_add_ticket',
        required: true, label: 'Serie Tickets: ', labelPosition: 'top'},
    {view: 'richselect', id: 'lst_sucursal_warehouse', name: 'sucursal_warehouse',
        label: 'Almacen: ', labelPosition: 'top', required: false, options: [], hidden: true},
    {view: 'button', id: 'cmd_add_sucursal', label: 'Agregar',
        autowidth: true, type: 'iconButton', icon: 'plus'},
    {maxWidth: 20},
]}]


var grid_sucursales_cols = [
    {id: 'id', header: 'ID', hidden: true},
    {id: 'delete', header: '', width: 30, css: 'delete'},
    {id: 'name', header: 'Nombre', fillspace: 1},
    {id: 'serie_invoice', header: 'Serie Facturas', fillspace: 1},
    {id: 'serie_tickets', header: 'Serie Tickets', fillspace: 1},
    {id: 'warehouse', header: 'Almacen', fillspace: 1, hidden: true},
]


var grid_sucursales = {
    view: 'datatable',
    id: 'grid_sucursales',
    select: 'row',
    adjust: true,
    headermenu: false,
    footer: true,
    columns: grid_sucursales_cols,
    on:{
        'data->onStoreUpdated':function(){
            this.data.each(function(obj, i){
                obj.delete = '-'
            })
        }
    },
}


var options_admin_sucursales = [
    {maxHeight: 10},
    {template: 'Agregar Sucursal', type: 'section'},
    {view: 'form', id: 'form_add_sucursal', rows: controls_add_sucursal},
    {template: 'Sucursales', type: 'section'},
    {cols: [{maxWidth: 10}, grid_sucursales, {maxWidth: 10}]},
    {maxHeight: 20},
]


var tab_options = {
    view: 'tabview',
    id: 'tab_options',
    animate: true,
    cells: [
        {header: 'Plantillas', body: {id: 'tab_admin_templates',
            rows: options_templates}},
        {header: 'Clientes y Proveedores', body: {id: 'tab_admin_partners',
            view: 'scrollview', body: {rows: options_admin_partners}}},
        {header: 'Productos y Servicios', body: {id: 'tab_admin_products',
            view: 'scrollview', body: {rows: options_admin_products}}},
        {header: 'Complementos', body: {id: 'tab_admin_complements',
            view: 'scrollview', body: {rows: options_admin_complements}}},
        {header: 'Otros', body: {id: 'tab_admin_otros', view: 'scrollview',
            body: {rows: options_admin_otros}}},
        {header: 'Sucursales', body: {id: 'tab_admin_sucursales', view: 'scrollview',
            body: {rows: options_admin_sucursales}}},
    ],
}


var utilidades_archivos = [
    {maxHeight: 5},
    {template: 'Importar archivo CFDI (XML)', type: 'section'},
    {view: 'form', id: 'form_upload_cfdixml', rows: [
        {cols: [{},
            {view: 'uploader', id: 'up_cfdixml', autosend: false, link: 'lst_cfdixml',
                value: 'Seleccionar archivo XML', upload: '/files/cfdixml'}, {}]},
        {cols: [{},
            {view: 'list',  id: 'lst_cfdixml', name: 'cfdixml',
                type: 'uploader', autoheight: true, borderless: true}, {}]},
        {cols: [{}, {view: 'button', id: 'cmd_subir_cfdixml',
            label: 'Importar CFDI'}, {}]},
    ]},
{}]


var tab_utilidades = {
    view: 'tabview',
    id: 'tab_utilidades',
    multiview: true,
    animate: true,
    cells: [
        {id: 'Utilidades', rows: utilidades_archivos},
    ],
}


var grid_admin_taxes_cols = [
    {id: 'id', header: 'ID', hidden: true},
    {id: 'delete', header: '', width: 30, css: 'delete'},
    {id: 'name', header: 'Nombre', adjust: 'data'},
    {id: 'tipo', header: 'Tipo'},
    {id: 'tasa', header: 'Tasa'},
    {id: 'activo', header: 'Activo', template: '{common.checkbox()}',
        editor: 'checkbox'},
    {id: 'default', header: 'Predeterminado', template: '{common.radio()}',
        adjust: 'header'},
]


var grid_admin_monedas_cols = [
    {id: 'id', header: 'ID', hidden: true},
    {id: 'key', header: 'Clave'},
    {id: 'name', header: 'Nombre', adjust: 'data'},
    {id: 'activo', header: 'Activa', template: '{common.checkbox()}',
        editor: 'checkbox'},
    {id: 'default', header: 'Predeterminada', template: '{common.radio()}',
        adjust: 'header'},
]


var grid_admin_bancos_cols = [
    {id: 'id', header: 'ID', hidden: true},
    {id: 'key', header: 'Clave', footer: {content: 'countRows', css: 'right'}},
    {id: 'name', header: 'Nombre', footer: 'Bancos', fillspace: true},
    {id: 'razon_social', header: 'Razón Social', fillspace: true},
    {id: 'rfc', header: 'RFC', width: 125, editor: 'text'},
    {id: 'activo', header: 'Activo', template: '{common.checkbox()}',
        editor: 'checkbox'},
]


var grid_admin_unidades_cols = [
    {id: 'id', header: 'ID', hidden: true},
    {id: 'delete', header: '', width: 30, css: 'delete'},
    {id: 'key', header: 'Clave'},
    {id: 'name', header: 'Nombre', adjust: 'data'},
    {id: 'activo', header: 'Activa', template: '{common.checkbox()}',
        editor: 'checkbox'},
    {id: 'default', header: 'Predeterminada', template: '{common.radio()}',
        adjust: 'header'},
]


var grid_admin_taxes = {
    view: 'datatable',
    id: 'grid_admin_taxes',
    select: 'cell',
    adjust: true,
    autoheight: true,
    autowidth: true,
    headermenu: true,
    columns: grid_admin_taxes_cols,
}


var grid_admin_monedas = {
    view: 'datatable',
    id: 'grid_admin_monedas',
    select: 'cell',
    adjust: true,
    autoheight: true,
    autowidth: true,
    headermenu: true,
    columns: grid_admin_monedas_cols,
}


var grid_admin_bancos = {
    view: 'datatable',
    id: 'grid_admin_bancos',
    select: 'cell',
    adjust: true,
    editable: true,
    headermenu: true,
    footer: true,
    columns: grid_admin_bancos_cols,
}


var grid_admin_unidades = {
    view: 'datatable',
    id: 'grid_admin_unidades',
    select: 'cell',
    adjust: true,
    autowidth: true,
    headermenu: true,
    columns: grid_admin_unidades_cols,
    on:{
        'data->onStoreUpdated':function(){
            this.data.each(function(obj, i){
                obj.delete = '-'
            })
        }
    },
}


var grid_admin_formasdepago_cols = [
    {id: 'id', header: 'ID', hidden: true},
    {id: 'key', header: 'Clave'},
    {id: 'name', header: 'Nombre', adjust: 'data'},
    {id: 'activo', header: 'Activa', template: '{common.checkbox()}',
        editor: 'checkbox'},
    {id: 'default', header: 'Predeterminada', template: '{common.radio()}',
        adjust: 'header'},
]


function format_bool_fisica(obj){
    if(obj.fisica){
        return 'Si'
    }else{
        return 'No'
    }
}


function format_bool_moral(obj){
    if(obj.moral){
        return 'Si'
    }else{
        return 'No'
    }
}


var grid_admin_usos_cfdi_cols = [
    {id: 'id', header: 'ID', hidden: true},
    {id: 'key', header: 'Clave', adjust: 'header'},
    {id: 'name', header: 'Nombre', width: 500},
    {id: 'fisica', header: 'Físicas', adjust: 'header',
        template: format_bool_fisica},
    {id: 'moral', header: 'Morales', adjust: 'header',
        template: format_bool_moral},
    {id: 'activo', header: 'Activa', template: '{common.checkbox()}',
        editor: 'checkbox', adjust: 'header'},
]


var grid_admin_regimenes_fiscales_cols = [
    {id: 'id', header: 'ID', hidden: true},
    {id: 'key', header: 'Clave', adjust: 'header'},
    {id: 'name', header: 'Nombre', width: 500},
    {id: 'fisica', header: 'Físicas', adjust: 'header',
        template: format_bool_fisica},
    {id: 'moral', header: 'Morales', adjust: 'header',
        template: format_bool_moral},
    {id: 'activo', header: 'Activa', template: '{common.checkbox()}',
        editor: 'checkbox', adjust: 'header'},
]


var grid_admin_formasdepago = {
    view: 'datatable',
    id: 'grid_admin_formasdepago',
    select: 'cell',
    adjust: true,
    autowidth: true,
    headermenu: true,
    footer: true,
    columns: grid_admin_formasdepago_cols,
}


var grid_admin_regimenes_fiscales = {
    view: 'datatable',
    id: 'grid_admin_regimenes_fiscales',
    select: 'cell',
    adjust: true,
    autowidth: true,
    headermenu: true,
    footer: true,
    columns: grid_admin_regimenes_fiscales_cols,
}


var grid_admin_usos_cfdi = {
    view: 'datatable',
    id: 'grid_admin_usos_cfdi',
    select: 'cell',
    adjust: true,
    autowidth: true,
    headermenu: true,
    footer: true,
    columns: grid_admin_usos_cfdi_cols,
}


var admin_taxes = [
    'ISR',
    'IVA',
    'IEPS',
    'ISH',
    'INSPECCION DE OBRA',
    'ICIC',
    'CEDULAR',
    'CMIC',
    'SUPERVISION',
    'MANO DE OBRA',
]

var admin_sat_impuestos = {cols: [{maxWidth: 15},
    {view: 'richselect', id: 'lst_admin_impuestos', label: 'Impuesto',
        options: admin_taxes, labelAlign: 'right', required: true},
    {view: 'text', id: 'txt_admin_tasa', label: 'Tasa', labelAlign: 'right',
        required: true},
    {view: 'button', id: 'cmd_agregar_impuesto', label: 'Agregar',
        autowidth: true, type: 'iconButton', icon: 'plus'},
{}],}


var msg_tax = 'Activa los impuestos que uses. El predeterminado se muestra primero'
var sat_impuestos = [
    {maxHeight: 20},
    {cols: [{maxWidth: 15}, {view: 'label', label: msg_tax}, {}]},
    {maxHeight: 20},
    {cols: [{maxWidth: 15}, admin_sat_impuestos]},
    {maxHeight: 20},
    {cols: [{maxWidth: 15}, grid_admin_taxes, {}]},
{}]


var suggest_sat_moneda = {
    view: 'gridsuggest',
    id: 'grid_moneda_found',
    name: 'grid_moneda_found',
    body: {
        autoConfig: false,
        scroll: true,
        autoheight: false,
        header: true,
        yCount: 10,
        columns: [
            {id: 'id', hidden: true},
            {id: 'key', adjust: 'data', header: 'Clave'},
            {id: 'name', adjust: 'data', header: 'Moneda'},
        ],
        dataFeed:function(text){
            if (text.length > 2){
                this.load('/values/satmonedas?key=' + text)
            }else{
                this.hide()
            }
        }
    },
}


var buscar_nueva_moneda = {
    view: 'search',
    id: 'buscar_nueva_moneda',
    label: 'Buscar Moneda en el catálogo del SAT',
    labelPosition: 'top',
    suggest: suggest_sat_moneda,
    placeholder: 'Por clave o moneda. Captura al menos tres letras',
}


var msg_moneda = 'Activa las monedas que uses. La predeterminada se muestra primero'
var sat_monedas = [
    {maxHeight: 20},
    {cols: [{maxWidth: 15}, {view: 'label', label: msg_moneda}, {}]},
    {maxHeight: 20},
    {cols: [{maxWidth: 15}, buscar_nueva_moneda, {}]},
    {maxHeight: 20},
    {cols: [{maxWidth: 15}, grid_admin_monedas, {}]},
{}]


var msg_bancos = 'Activar los bancos necesarios'
var sat_bancos = [
    {maxHeight: 20},
    {cols: [{maxWidth: 15}, {view: 'label', label: msg_bancos}, {}]},
    {maxHeight: 20},
    {cols: [{maxWidth: 15}, grid_admin_bancos]},
    {maxHeight: 20},
]


var suggest_sat_unidad = {
    view: 'gridsuggest',
    id: 'grid_unidad_found',
    name: 'grid_unidad_found',
    body: {
        autoConfig: false,
        scroll:true,
        autoheight:false,
        header: true,
        yCount: 10,
        columns: [
            {id: 'id', hidden: true},
            {id: 'key', adjust: 'data', header: 'Clave'},
            {id: 'name', adjust: 'data', header: 'Unidad'},
        ],
        dataFeed:function(text){
            if (text.length > 1){
                this.load('/values/satunidades?key=' + text)
            }else{
                this.hide()
            }
        }
    },
}


var buscar_nueva_unidad = {
    view: 'search',
    id: 'buscar_nueva_unidad',
    label: 'Buscar Unidad en el catálogo del SAT',
    labelPosition: 'top',
    suggest: suggest_sat_unidad,
    placeholder: 'Por clave o descripción. Captura al menos tres letras',
}


var msg_unidades = 'Activar las unidades necesarias'
var sat_unidades = [
    {maxHeight: 20},
    {cols: [{maxWidth: 15}, {view: 'label', label: msg_unidades}, {}]},
    {maxHeight: 20},
    {cols: [{maxWidth: 15}, buscar_nueva_unidad, {}]},
    {maxHeight: 20},
    {cols: [{maxWidth: 15}, grid_admin_unidades, {}]},
    {maxHeight: 20},
]


var msg_formasdepago = 'Administrar las formas de pago.'
var sat_formasdepago = [
    {maxHeight: 20},
    {cols: [{maxWidth: 15}, {view: 'label', label: msg_formasdepago}, {}]},
    {maxHeight: 20},
    {cols: [{maxWidth: 15}, grid_admin_formasdepago, {}]},
    {maxHeight: 20},
]


var msg_usos_cfdi = 'Administrar Usos del CFDI.'
var sat_usos_cfdi = [
    {maxHeight: 20},
    {cols: [{maxWidth: 15}, {view: 'label', label: msg_usos_cfdi}, {}]},
    {maxHeight: 20},
    {cols: [{maxWidth: 15}, grid_admin_usos_cfdi, {}]},
    {maxHeight: 20},
]


var msg_regimenes_fiscales = 'Administrar Regimenes Fiscales.'
var sat_regimenes_fiscales = [
    {maxHeight: 20},
    {cols: [{maxWidth: 15}, {view: 'label', label: msg_regimenes_fiscales}, {}]},
    {maxHeight: 20},
    {cols: [{maxWidth: 15}, grid_admin_regimenes_fiscales, {}]},
    {maxHeight: 20},
]


var suggest_sat_unidades_peso = {
    view: 'gridsuggest',
    id: 'grid_unidadpeso_found',
    name: 'grid_unidadpeso_found',
    body: {
        autoConfig: false,
        scroll:true,
        autoheight:false,
        header: true,
        yCount: 10,
        columns: [
            {id: 'id', hidden: true},
            {id: 'key', adjust: 'data', header: 'Clave'},
            {id: 'name', adjust: 'data', header: 'Unidad'},
        ],
        dataFeed:function(text){
            if (text.length > 1){
                this.load('/values/satunidadespeso?key=' + text)
            }else{
                this.hide()
            }
        }
    },
}


var buscar_carta_unidades_peso = {
    view: 'search',
    id: 'buscar_carta_unidades_peso',
    label: 'Buscar Unidad de Peso en el catálogo del SAT',
    labelPosition: 'top',
    suggest: suggest_sat_unidades_peso,
    placeholder: 'Por clave o descripción. Captura al menos tres letras',
}


var columns_carta_unidades_peso = [
    {id: 'id', header: 'ID', hidden: true},
    {id: 'delete', header: '', width: 30, css: 'delete'},
    {id: 'key', header: 'Clave'},
    {id: 'name', header: 'Nombre', adjust: 'data'},
    {id: 'activo', header: 'Activo', template: '{common.checkbox()}',
        editor: 'checkbox'},
]


var grid_carta_unidades_peso = {
    view: 'datatable',
    id: 'grid_carta_unidades_peso',
    url: 'satunidadespeso?opt=all',
    select: 'cell',
    adjust: true,
    autowidth: true,
    headermenu: true,
    columns: columns_carta_unidades_peso,
    on:{
        'data->onStoreUpdated':function(){
            this.data.each(function(obj, i){
                obj.delete = '-'
            })
        }
    },
}


var carta_porte_unidades_peso = [
    {maxHeight: 20},
    {cols: [{maxWidth: 15}, buscar_carta_unidades_peso, {}]},
    {maxHeight: 20},
    {cols: [{maxWidth: 15}, grid_carta_unidades_peso, {}]},
    {maxHeight: 20},
]


var tab_sat_carta_porte = [{
    view: 'tabview',
    id: 'tab_sat_carta_porte',
    multiview: true,
    animate: true,
    cells: [
        {id: 'Unidades de Peso', rows: carta_porte_unidades_peso},
    ]
}]


var tab_sat = {
    view: 'tabview',
    id: 'tab_sat',
    multiview: true,
    animate: true,
    cells: [
        {id: 'Impuestos', rows: sat_impuestos},
        {id: 'Monedas', rows: sat_monedas},
        {id: 'Bancos', rows: sat_bancos},
        {id: 'Unidades', rows: sat_unidades},
        {id: 'Formas de Pago', rows: sat_formasdepago},
        {id: 'Usos de CFDI', rows: sat_usos_cfdi},
        {id: 'Regimenes Fiscales', rows: sat_regimenes_fiscales},
        {id: 'Carta Porte', rows: tab_sat_carta_porte},
    ],
}


var usuarios_agregar = [{cols: [
    {maxWidth: 20},
    {view: 'text', id: 'txt_usuario_usuario', name: 'usuario_usuario',
        label: 'Usuario: ', labelPosition: 'top', required: true},
    {view: 'text', id: 'txt_usuario_contra1', name: 'usuario_contra1',
        required: true,  label: 'Contraseña: ', type: 'password',
        labelPosition: 'top'},
    {view: 'text', id: 'txt_usuario_contra2', name: 'usuario_contra2',
        required: true, label: 'Confirmación de contraseña: ',
        type: 'password', labelPosition: 'top'},
    {view: 'button', id: 'cmd_usuario_agregar', label: 'Agregar',
        autowidth: true, type: 'iconButton', icon: 'plus'},
    {maxWidth: 20},
]}]


var grid_usuarios_cols = [
    {id: 'id', header: 'ID', hidden: true},
    {id: 'delete', header: '', width: 30, css: 'delete'},
    {id: 'usuario', header: 'Usuario', fillspace: 1},
    {id: 'nombre', header: 'Nombre', fillspace: 1},
    {id: 'apellidos', header: 'Apellidos', fillspace: 2},
    {id: 'correo', header: 'Correo Electrónico', fillspace: 2},
    {id: 'fecha_ingreso', header: 'Fecha de Ingreso', fillspace: 1,
        hidden: true},
    {id: 'ultimo_ingreso', header: 'Ultimo Ingreso', fillspace: 1,
        hidden: true},
    {id: 'in_branch', header: 'En Sucursal', template: '{common.checkbox()}',
        editor: 'checkbox', adjust: 'header', hidden: true},
    {id: 'es_activo', header: 'Activo', template: '{common.checkbox()}',
        editor: 'checkbox', adjust: 'header'},
    {id: 'es_admin', header: 'Es Admin', template: '{common.checkbox()}',
        editor: 'checkbox', adjust: 'header'},
    {id: 'es_superusuario', header: 'Es SU', template: '{common.checkbox()}',
        editor: 'checkbox', adjust: 'header', hidden: true},
]


var grid_usuarios = {
    view: 'datatable',
    id: 'grid_usuarios',
    select: 'row',
    adjust: true,
    headermenu: false,
    footer: true,
    columns: grid_usuarios_cols,
    on:{
        'data->onStoreUpdated':function(){
            this.data.each(function(obj, i){
                obj.delete = '-'
            })
        }
    },
}


var usuarios_admin = [
    {maxHeight: 10},
    {template: 'Agregar Usuario', type: 'section'},
    {view: 'form', id: 'form_usuario', rows: usuarios_agregar},
    {maxHeight: 20},
    {template: 'Usuarios Registrados', type: 'section'},
    {cols: [{maxWidth: 10}, grid_usuarios, {maxWidth: 10}]},
    {maxHeight: 20},
    {template: 'Opciones', type: 'section'},
    {cols: [{view: 'checkbox', id: 'chk_users_notify_access', labelWidth: 15,
        labelRight: 'Notificar accesos al sistema (solo a administradores)'}]},
    {},
]


var tab_usuarios = {
    view: 'tabview',
    id: 'tab_usuarios',
    multiview: true,
    animate: true,
    cells: [
        {id: 'Usuarios', rows: usuarios_admin},
    ],
}


var app_emisor = {
    id: 'app_emisor',
    rows:[
        {view: 'template', id: 'th_emisor', type: 'header',
            template: 'Emisor'},
        form_emisor,
        {maxHeight: 20},
        {margin: 10, cols: [{},
            {view: 'button', id: 'cmd_save_emisor', label: 'Guardar' ,
                type: 'form', autowidth: true, align: 'center'},
            {}]
        },
        {maxHeight: 20},
    ],
}


var app_folios = {
    id: 'app_folios',
    rows:[
        {view: 'template', id: 'th_folios', type: 'header',
            template: 'Folios'},
        form_folios,
    ],
}


var app_correo = {
    id: 'app_correo',
    rows:[
        {view: 'template', id: 'th_correo', type: 'header',
            template: 'Configuración de correo'},
        form_correo,
    ],
}


var app_sat = {
    id: 'app_sat',
    rows:[
        {view: 'template', id: 'th_sat', type: 'header',
            template: 'Catálogos del SAT'},
        tab_sat,
    ],
}


var app_usuarios = {
    id: 'app_usuarios',
    rows:[
        {view: 'template', id: 'th_usuarios', type: 'header',
            template: 'Administración de Usuarios'},
        tab_usuarios,
    ],
}


var app_options = {
    id: 'app_options',
    rows:[
        {view: 'template', id: 'th_options', type: 'header',
            template: 'Opciones'},
        tab_options,
    ],
}


var app_utilidades = {
    id: 'app_utilidades',
    rows:[
        {view: 'template', id: 'th_utilidades', type: 'header',
            template: 'Herramientas'},
        tab_utilidades,
    ],
}


var multi_admin = {
    id: 'multi_admin',
    animate: true,
    cells:[
        {
            id: 'app_admin_home',
            view: 'template',
            template: 'Admin Inicio'
        },
        app_emisor,
        app_folios,
        app_correo,
        app_sat,
        app_usuarios,
        app_options,
        app_utilidades,
    ],
}


var menu_user = {
    view: 'menu',
    id: 'menu_user',
    width: 150,
    autowidth: true,
    data: [
        {id: '0', value: 'User...', submenu:[{id:1, value:'Cerrar Sesión'}]},
    ],
    type: {
        subsign: true,
    },
}


var ui_admin = {
    rows: [
        {view: 'toolbar', padding: 3, elements: [
            {view: 'button', type: 'icon', icon: 'bars',
                width: 37, align: 'left', css: 'app_button', click: function(){
                    $$('sidebar_admin').toggle()
                }
            },
            {view: 'label', label: 'Empresa Libre - Configuración'},
            {},
            {view: 'button', type: 'icon', width: 40, css: 'app_button',
                icon: 'home', click: 'cmd_home_click'},
            menu_user
        ]},
        {
            cols:[
                sidebar_admin,
                multi_admin,
            ]
        }
    ]
}



var body_win_emisor_logo = [
    {view: 'uploader', id: 'up_emisor_logo', autosend: true, link: 'lst_logo',
        value: 'Seleccionar logotipo', upload: '/files/emisorlogo', width: 200,
        accept: "image/png, image/gif, image/jpeg"},
    {view: 'list',  id: 'lst_logo', name: 'logo',
        type: 'uploader', autoheight:true, borderless: true},
    {},
    {cols: [{}, {view: 'button', label: 'Cerrar', autowidth: true,
        click:("$$('win_emisor_logo').close();")}, {}]}
]




var grid_cols_admin_leyendas_fiscales = [
    {id: 'id', header: 'ID', hidden: true},
    {id: 'delete', header: '', width: 30, css: 'delete'},
    {id: 'texto_leyenda', header: 'Leyenda', fillspace: 1},
    {id: 'norma', header: 'Norma', fillspace: 1},
    {id: 'disposicion_fiscal', header: 'Disposición Fiscal', fillspace: 1},
    //~ {id: 'active', header: 'Activa', template: '{common.checkbox()}',
        //~ editor: 'checkbox'},
]


var grid_admin_leyendas_fiscales = {
    view: 'datatable',
    id: 'grid_admin_leyendas_fiscales',
    select: 'row',
    adjust: true,
    autoheight: true,
    headermenu: true,
    columns: grid_cols_admin_leyendas_fiscales,
    on:{
        'data->onStoreUpdated':function(){
            this.data.each(function(obj, i){
                obj.delete = '-'
            })
        }
    },
}


var form_controls_admin_leyendas_fiscales = [
    {cols: [
        {view: 'text', id: 'txt_texto_leyenda', label: 'Leyenda', width: 200,
            labelPosition: 'top', name: 'texto_leyenda', required: true},
        {view: "text", id: 'txt_norma_fiscal', label: 'Norma', width: 200,
            name: 'norma', labelPosition: 'top'},
        {view: "text", id: 'txt_disposicion_fiscal', label: 'Disposición',
            name: 'disposicion_fiscal', labelPosition: 'top', width: 200}
    ]},
    {cols: [{},
    {view: 'button', type: 'form', icon: 'plus', label: 'Agregar', autowidth: true,
        click: function(){add_admin_leyenda_fiscal_click()}
        }, {}]},
    grid_admin_leyendas_fiscales,
    {},
    {cols:[{},
        {view: 'button', value: 'Cerrar', click: "$$('win_leyendas_fiscales').close()"},
    {}]}
]


var admin_ui_leyendas_fiscales = {
    init: function(){
        webix.ui({
            view: 'window',
            id: 'win_leyendas_fiscales',
            head: 'Leyendas Fiscales',
            width: 800,
            modal: true,
            position: 'center',
            body: {
                view: 'form', id: 'form_admin_leyendas_fiscales',
                elements: form_controls_admin_leyendas_fiscales
            }
        })

        $$('grid_admin_leyendas_fiscales').attachEvent('onItemClick', grid_admin_leyendas_fiscales_click)

    },
}



var body_set_branch_user = {rows: [{minHeight: 10},
    {view: 'text', id: 'txt_user_id', readonly: true, hidden: true},
    //~ {view: 'text', id: 'txt_user_name', label: 'Usuario', readonly: true},
    {view: 'richselect', id: 'lst_branchs', name: 'lst_branchs',
        label: 'Sucursales: ', required: true, options: []},
    {minHeight: 10},
    {cols: [{},
        {view: 'button', id: 'cmd_set_branch_user_save', label: 'Guardar'}, {},
        {view: 'button', id: 'cmd_set_branch_user_cancel', label: 'Cancelar', type: 'danger'}, {}
        ]},
    {minHeight: 20},
]}


var win_set_branch_user = {
    init: function(){
        webix.ui({
            view: 'window',
            id: 'win_set_branch_user',
            width: 400,
            modal: true,
            position: 'center',
            head: 'Asignar Sucursal',
            body: body_set_branch_user,
        })
        $$('cmd_set_branch_user_save').attachEvent('onItemClick', cmd_set_branch_user_save_click)
        $$('cmd_set_branch_user_cancel').attachEvent('onItemClick', cmd_set_branch_user_cancel_click)
    }
}
