// JavaScript Document
//funciones de acciones sobre la informacion

function Asc(String) {
    return String.charCodeAt(0);
}

function Chr(AsciiNum) {
    return String.fromCharCode(AsciiNum)
}

//var cr= new Array(" ","A","B","C","D","E","F","G","H","I","J","K","L","M","N","*","O","P","Q","R","S","T","U","V","W","X","Y","Z","'","(",")","=","_","|","0","1","2","3","4","5","6","7","8","9",".",",");

function eCr(lcCadena) {
    v1 = 7;
    v2 = 1;
    tam = cr.length;
    lcCadena = lcCadena.toUpperCase().trim();
    cryp = "";
    for (i = 0; i < lcCadena.length; i++) {
        numx = 0;
        let = lcCadena.substring(i, i + 1);
        numx = cr.indexOf(let);
        resop = v1 * numx + v2;
        md = resop % tam;
        cryp = cryp + "" + cr[md];
    }
    return cryp;
}


function dCr(lcCadena) {
    v1 = 7;
    v2 = 1;
    tam = cr.length;
    lcCadena = lcCadena.toUpperCase().trim();
    inv = 33;
    dcryp = "";
    for (i = 0; i < lcCadena.length; i++) {
        numx = 0;
        let = lcCadena.substring(i, i + 1);
        numx = cr.indexOf(let);
        resop = (numx - v2) * inv;
        md = resop % tam;
        if (md < 0) {
            while (md < 0) {
                md = md + tam;
            }
        }
        dcryp = dcryp + "" + cr[md];
    }

    return dcryp;
}

function dCrip(lcCadena, lcPatron) {
    lcR = ""
    if (lcPatron == "") {
        lcPatron = "ABCDEFGHIJ"
    }

    lcCadena = lcCadena.replace("__________", Chr(39))
    lcCadena = lcCadena.replace("++++++++++", Chr(0))

    for (lnI = 0; lnI < lcCadena.length; lnI++) {
        lnC1 = Asc(lcCadena.substring(lnI, lnI + 1))
        if (lnI > lcPatron.length - 1) {
            lnPos = (lnI % (lcPatron.length - 1))
            lnC2 = Asc(lcPatron.substring(lnPos, lnPos + 1))
        }
        else {
            lnC2 = Asc(lcPatron.substring(lnI, lnI + 1))
        }
        lnC1 = lnC1 - lnC2 - 64
        if (lnC1 < 0) {
            lnC1 = 256 + lnC1
        }
        lcR = lcR + Chr(lnC1)
    }
    return lcR
}

function eCrip(lcCadena, lcPatron) {
    lcR = ""
    if (lcPatron == "") {
        lcPatron = "ABCDEFGHIJ"
    }
    for (lnI = 0; lnI < lcCadena.length; lnI++) {
        lnC1 = Asc(lcCadena.substring(lnI, lnI + 1))

        if (lnI > lcPatron.length - 1) {
            lnPos = (lnI % (lcPatron.length - 1))
            lnC2 = Asc(lcPatron.substring(lnPos, lnPos + 1))
        }
        else {
            lnC2 = Asc(lcPatron.substring(lnI, lnI + 1))
        }
        lnC1 = lnC1 + lnC2 + 64
        if (lnC1 > 255) {
            lnC1 = lnC1 - 256
        }

        switch (lnC1) {
            case 39 :
                lcR = lcR + "__________"
                break;
            case 0 :
                lcR = lcR + "++++++++++"
                break;
            default:
                lcR = lcR + Chr(lnC1)
        }
    }
    return lcR
}

function sleep(milliseconds) {
    var start = new Date().getTime();
    for (var i = 0; i < 1e7; i++) {
        if ((new Date().getTime() - start) > milliseconds) {
            break;
        }
    }
}

function btnNuevoColorbox(grilla, info) {
    if (info.nom_pag.indexOf("#") !== 0) {
        pager = "#" + info.nom_pag;
    } else {
        pager = info.nom_pag;
    }
    grilla.navSeparatorAdd(pager);

    var editurl = grilla.jqGrid('getGridParam', 'editurl'), b = true;
    grilla.navButtonAdd(pager, {
        caption: "",
        id: "new_" + info.nom_pag,
        buttonicon: 'ui-btn-new',
        title: info.title,
        onClickButton: function () {
            if (info.validar) {
                if ($.isFunction(info.validar)) {
                    b = info.validar();
                } else {
                    b = true;
                }
            }

            if (b) {
                $.fn.colorbox({
                    href: editurl + info.param,
                    width: info.ancho,
                    height: info.alto,
                    title: info.title,
                    transition: 'elastic',
                    iframe: info.iframe,
                });
            }
        },
        position: "last"
    });
    //$(pager).find(".ui-icon-plus").css({"background-image":"url('images/nuevo.png')", "background-position":"0","width":"16px","height":"16px","cursor":"pointer"});
}

function btnEditarColorbox(grilla, info) {
    if (info.nom_pag.indexOf("#") !== 0) {
        pager = "#" + info.nom_pag;
    } else {
        pager = info.nom_pag;
    }
    grilla.navSeparatorAdd(pager);
    var editurl = grilla.jqGrid('getGridParam', 'editurl')

    grilla.navButtonAdd(pager, {
        caption: "",
        id: "edit_" + info.nom_pag,
        buttonicon: 'ui-icon-pencil',
        title: info.title,
        onClickButton: function () {
            var gr = jQuery("#" + info.ide_tabla).getGridParam("selrow");
            if (gr != null) {
                $.fn.colorbox({
                    href: editurl + info.param + "&codigo=" + gr,
                    width: info.ancho,
                    height: info.alto,
                    title: info.title,
                    transition: 'elastic',
                    iframe: info.iframe,
                });
            } else {
                jAlert(info.msg_sel, info.empresa);
            }
        },
        position: "last"
    });
    $(pager).find(".ui-icon-pencil").css({"background-image": "url('images/editar.png')", "background-position": "center", "width": "16px", "height": "16px", "cursor": "pointer"});
}

function btnEliminar(grilla, infox) {
    var datos_normales = {
        title: '',
        caption: '',
        modulo: '',
        ide_tabla: '',
        url: grilla.jqGrid('getGridParam', 'editurl'),
        nom_pag: grilla.jqGrid('getGridParam', 'pager'),
        isgrid: true,
        msgExito: '',
        msg_confirma: '',
        recarga: '',
        adicional: null,
        msg_sel: '',
        data: function () {
            return {}
        },
    }

    var info = $.extend(datos_normales, infox)

    if (info.nom_pag.indexOf("#") !== 0) {
        pag = "#" + info.nom_pag;
    } else {
        pag = info.nom_pag;
    }

    grilla.navSeparatorAdd(pag);

    var modulo = info.modulo;

    grilla.navButtonAdd(pag, {
        caption: info.caption,
        buttonicon: 'ui-icon-trash',
        title: info.title,
        id: 'del_t' + info.ide_tabla,
        onClickButton: function () {
            var gr = jQuery("#" + info.ide_tabla).getGridParam("selrow");
            var dts = grilla.getRowData(gr);
            if (gr != null) {
                jConfirm(info.msg_confirma, info.empresa, function (r) {
                    if (r) {
                        dtsE = info.data();
                        $.extend(dtsE, {oper: 'del', id: gr});
                        $.ajax({
                            type: "POST",
                            url: info.url,
                            data: dtsE,
                            async: false,
                            success: function (rta) {
                                var rta = $.parseJSON(rta);
                                if (rta['error'] != 0) {
                                    if (rta['error'] == 'session') {
                                        modulo = 'global'
                                    }
                                    jAlert(getMsg(modulo, rta['error']), info.empresa, function () {
                                        if (rta['error'] == 'session') {
                                            location.reload();
                                        }
                                    });
                                } else {
                                    if (info.recarga) {
                                        grilla.trigger('reloadGrid');
                                        notifica_ok(info.msgExito);
                                    } else {
                                        grilla.delRowData(gr);
                                        notifica_ok(info.msgExito);
                                    }
                                    if ($.isFunction(info.adicional)) {
                                        info.adicional(rta, dts);
                                    }
                                }
                            }
                        });
                    }
                });
            } else {
                jAlert(info.msg_sel, info.empresa);
            }
        },
        position: "last"
    });
    $(pag).find(".ui-icon-trash").css({"background-image": "url('images/eliminar.png')", "background-position": "center", "width": "16px", "height": "16px", "cursor": "pointer"});
}

/*-------------------------------------------------------------------------------------------------------------------------------------------------------
 Coloca un boton para agregar un nuevoregistro  deacuaerdo al formato que arma  la grilla
 -------------------------------------------------------------------------------------------------------------------------------------------------------*/
function btnNewReginLine(grilla, info) {
    var new_id = Math.random()
    if (info.nom_pag.indexOf("#") !== 0) {
        pag = "#" + info.nom_pag;
    } else {
        pag = info.nom_pag;
    }
    grilla.navButtonAdd(pag, {
        caption: "",
        buttonicon: 'ui-icon-plus',
        title: info.title,
        onClickButton: info.Click,
        position: "last"
    });
    $(pag).find(".ui-icon-plus").css({"background-image": "url('images/nuevo.png')", "background-position": "center", "width": "16px", "height": "16px", "cursor": "pointer"});
}

/*-------------------------------------------------------------------------------------------------------------------------------------------------------
 Coloca un boton para agregar un nuevoregistro  deacuaerdo al formato que arma  la grilla
 -------------------------------------------------------------------------------------------------------------------------------------------------------*/

function btnNuevoNor(grilla, infox) {
    if (infox.ide_tabla == "") {
        alert("Faltan paarmetros en la funciónn");
        return false
    }
    ;
    if (infox.ide_tabla.indexOf("#") !== 0) {
        frm = "#FrmGrid" + infox.ide_tabla
    } else {
        frm = "#FrmGrid" + infox.ide_tabla.substring(1)
    }
    ;

    var datos_normales = {
        modulo: '',
        caption: '',
        title: '',
        ide_tabla: '',
        nom_pag: '',
        modal: true,
        ancho: 'auto',
        recarga: false,
        closeAfterAdd: true,
        recreateForm: true,
        msgExito: '',
        msg_cmps_oblg: '',
        empresa: '',
        msgExito:'',
                nom_pag:'',
                adicional: null,
        beforeShowForm: null,
        afterShowForm: null,
        beforeSubmit: function () {
            if ($(":input, select, textarea", frm).hasClass('campos_error')) {
                jAlert(info.msg_cmps_oblg, info.empresa)
            } else {
                return [true]
            }
        }
    }
    var info = $.extend(datos_normales, infox)



    if (infox.nom_pag.indexOf("#") !== 0) {
        pag = "#" + info.nom_pag;
    } else {
        pag = info.nom_pag;
    }

    grilla.navSeparatorAdd(pag);
    var pager = grilla.jqGrid('getGridParam', 'pager')
    var modulo = info.modulo;
    grilla.navButtonAdd(pag, {
        caption: "",
        buttonicon: 'ui-icon-plus',
        title: info.title,
        onClickButton: function () {
            jQuery("#" + info.ide_tabla).jqGrid('editGridRow', 'new', {
                reloadAfterSubmit: info.recarga,
                modal: info.modal,
                afterShowForm: info.afterShowForm,
                beforeShowForm: info.beforeShowForm,
                width: info.ancho,
                closeAfterAdd: info.closeAfterAdd,
                recreateForm: info.recreateForm, //buelve a crear el formulario
                beforeSubmit: info.beforeSubmit,
                afterSubmit: function (xhr, postdata) {
                    rta = $.parseJSON(xhr.responseText);
                    if (rta['error'] == 0) {
                        notifica_ok(info.msgExito);
                        $("#" + info.ide_tabla).setSelection(rta['id'])
                        if ($.isFunction(info.adicional)) {
                            info.adicional(rta, postdata);
                        }
                        return [true, '', rta['id']]
                    } else {
                        if (rta['error'] == 'session')
                            modulo = 'global'
                        jAlert(getMsg(modulo, rta['error']), info.empresa, function () {
                            if (rta['error'] == 'session')
                                location.reload();
                        })
                        return [true];
                    }
                },
            });
        },
        position: "last"
    });
    $(pag).find(".ui-icon-plus").css({"background-image": "url('images/nuevo.png')", "background-position": "center", "width": "16px", "height": "16px", "cursor": "pointer"});
}

/*-------------------------------------------------------------------------------------------------------------------------------------------------------
 //funcion para agreagar un boton de editar a la grilla; este boston se crea con respecto a los datos y formato de la grilla
 -------------------------------------------------------------------------------------------------------------------------------------------------------*/

function btnEditarNor(grilla, infox) {
    var datos_normales = {
        modulo: '',
        caption: '',
        title: '',
        ide_tabla: '',
        nom_pag: grilla.jqGrid('getGridParam', 'pager'),
        modal: true,
        ancho: 'auto',
        recarga: false,
        closeAfterEdit: true,
        recreateForm: true,
        msgExito: '',
        msg_cmps_oblg: '',
        empresa: '',
        msg_sel: '',
        frm: "",
        msgExito:'',
                nom_pag:'',
                adicional: '',
    }

    var info = $.extend(datos_normales, infox)

    if (info.ide_tabla == "") {
        alert("Faltan paarmetros en la funciónn");
        return false
    }
    ;
    if (info.ide_tabla.indexOf("#") !== 0) {
        frm = "#FrmGrid" + info.ide_tabla
    } else {
        frm = "#FrmGrid" + info.ide_tabla.substring(1)
    }
    ;

    if (info.nom_pag.indexOf("#") !== 0) {
        pag = "#" + info.nom_pag;
    } else {
        pag = info.nom_pag;
    }
    grilla.navSeparatorAdd(pag);

    var modulo = info.modulo;
    grilla.navButtonAdd(pag, {
        caption: info.caption,
        buttonicon: 'ui-icon-pencil',
        title: info.title,
        onClickButton: function () {
            var gr = jQuery("#" + info.ide_tabla).getGridParam("selrow");
            if (gr != null) {
                jQuery("#" + info.ide_tabla).jqGrid('editGridRow', gr, {
                    reloadAfterSubmit: info.recarga,
                    modal: info.modal,
                    recreateForm: info.recreateForm,
                    width: info.ancho,
                    closeAfterEdit: info.closeAfterEdit,
                    beforeSubmit: function () {
                        if ($(":input, select, textarea", frm).hasClass('campos_error')) {
                            jAlert(info.msg_cmps_oblg, info.empresa)
                            return
                        } else {
                            return [true]
                        }
                    },
                    afterSubmit: function (xhr, postdata) {
                        var rta = $.parseJSON(xhr.responseText);
                        if (rta['error'] == 0) {
                            notifica_ok(info.msgExito);
                            if ($.isFunction(info.adicional)) {
                                info.adicional(rta, postdata);
                            }
                            return [true]
                        } else {
                            if (rta['error'] == 'session')
                                modulo = 'global'
                            jAlert(getMsg(modulo, rta['error']), info.empresa, function () {
                                if (rta['error'] == 'session')
                                    location.reload();
                            })
                            return [true];
                        }
                    },
                });
            } else {
                jAlert(info.msg_sel, info.empresa);
            }
            ;
        },
        position: "last"
    });
    $(pag).find(".ui-icon-pencil").css({"background-image": "url('images/editar.png')", "background-position": "center", "width": "16px", "height": "16px", "cursor": "pointer"});
}

function btnEliminarNor(grilla, info) {
    if (info.nom_pag.indexOf("#") !== 0) {
        pag = "#" + info.nom_pag;
    } else {
        pag = info.nom_pag;
    }
    grilla.navSeparatorAdd(pag);
    var modulo = info.modulo;
    grilla.navButtonAdd(pag, {
        caption: "",
        buttonicon: 'ui-icon-trash',
        title: info.title,
        onClickButton: function () {
            var gr = jQuery("#" + info.ide_tabla).getGridParam("selrow");
            if (gr != null) {
                jQuery("#" + info.ide_tabla).jqGrid('delGridRow', gr, {
                    reloadAfterSubmit: info.recarga,
                    msg: info.msg_confirma,
                    bSubmit: "Si",
                    bCancel: "No",
                    modal: info.modal,
                    width: info.ancho,
                    resize: false,
                    afterSubmit: function (xhr, postdata) {
                        rta = xhr.responseText;
                        if (rta == 0) {
                            return [true]
                            notifica_ok(info.msgExito);
                        } else {
                            if (rta == 'session')
                                modulo = 'global'
                            jAlert(getMsg(modulo, rta), info.empresa, function () {
                                if (rta == 'session')
                                    location.reload();
                            })
                            return [true];
                        }
                    },
                });
            } else {
                jAlert(info.msg_sel, info.empresa);
            }
            ;
        },
        position: "last"
    });
}

/*-------------------------------------------------------------------------------------------------------------------------------------------------------
 funcion para cambiar los iconos basiscos de la grilla como : paginadores, busqueda y reset
 -------------------------------------------------------------------------------------------------------------------------------------------------------*/

function cambiar_iconos(pager) {
    $("#" + pager).find(".ui-icon-search").css({"background-image": "url('images/buscar.png')", "background-position": "center", "width": "16px", "height": "16px"});
    $("#" + pager).find(".ui-icon-refresh").css({"background-image": "url('images/refresh.png')", "background-position": "center", "width": "16px", "height": "16px"});

    //btn Siguiente
    $("#" + pager).find(".ui-icon-seek-first").css({"background-image": "url('images/first.png')", "background-position": "center", "width": "16px", "height": "16px"});
    //btn Anterior
    $("#" + pager).find(".ui-icon-seek-prev").css({"background-image": "url('images/previous.png')", "background-position": "center", "width": "16px", "height": "16px"});

    //btn Siguiente
    $("#" + pager).find(".ui-icon-seek-next").css({"background-image": "url('images/next.png')", "background-position": "center", "width": "16px", "height": "16px"});
    //btn Ultimo
    $("#" + pager).find(".ui-icon-seek-end").css({"background-image": "url('images/last.png')", "background-position": "center", "width": "16px", "height": "16px"});

}
/*-------------------------------------------------------------------------------------------------------------------------------------------------------
 //funcion para mandar a guardar informacion de un formulario a la base de datos  (Guardar o editar) 
 -------------------------------------------------------------------------------------------------------------------------------------------------------*/

function acciones(infox) {
    $(document).ready(function () {
        var datos_normales = {
            url: '',
            data: [],
            frm: "",
            modulo: '',
            ide_tabla: '',
            id_grilla: '',
            recarga: false,
            msg_cmps_oblg: '',
            msg_espere: '',
            msgExito: '',
            empresa: '',
            data_grid: {},
            adicional: null,
            evento: 'new',
        }

        var info = $.extend(datos_normales, infox)
        if (info.frm == "") {
            alert("Faltan paarmetros en la funciónn");
            return false
        }
        ;
        if (info.frm.indexOf("#") !== 0) {
            frm = "#" + info.frm
        } else {
            frm = info.frm
        }
        ;

        if (!$(":input, select, textarea", frm).hasClass('campos_error')) {
            $.ajax({
                type: "POST",
                url: info.url,
                data: info.data,
                dataType: "html",
                beforeSend: function () {
                    $.blockUI({message: info.msg_espere});
                },
                success: function (rtax) {
                    $.unblockUI();
                    var rta = $.parseJSON(rtax)
                    if (rta['error'] != 0) {
                        if (rta['error'] == 'session') {
                            info['modulo'] = 'global'
                        }
                        jAlert(getMsg(info.modulo, rta['error']), info.empresa, function () {
                            if (rta['error'] == 'session') {
                                $.fn.colorbox.close();
                                location.reload();
                            }
                        });
                    } else {
                        $.fn.colorbox.close();
                        if (info.recarga) {
                            $("#" + info.id_grilla).trigger('reloadGrid');
                        } else {
                            if (info.evento == 'new') {
                                jQuery("#" + info.id_grilla).addRowData(rta['id'], info.data_grid);
                            } else {
                                jQuery("#" + info.id_grilla).setRowData(rta['id'], info.data_grid);
                            }
                        }
                        notifica_ok(info.msgExito);
                        if ($.isFunction(info.adicional)) {
                            info.adicional(rta, info.data);
                        }
                    }
                },
            });
        } else {
            jAlert(info.msg_cmps_oblg, info.empresa)
        }
    });
}
function gralEliminar(infox) {
    var datos_normales = {
        url: '',
        data: {oper: 'del'},
        modulo: '',
        msg_espere: '',
        msgExito: '',
        empresa: 'Academia',
        adicional: null,
        async: false,
        msg_confirma: ""
    }
    //datos_normales.data=$.extend(datos_normales.data,infox.data);
    var info = $.extend(true, datos_normales, infox);
//	var dataEnv=$.extend(datos_normales,infox);
    jConfirm(info.msg_confirma, info.empresa, function (r) {
        if (r) {
            $.ajax({
                type: "POST",
                url: info.url,
                data: info.data,
                async: info.async,
                success: function (rta) {
                    var rta = $.parseJSON(rta);
                    if (rta['error'] != 0) {
                        if (rta['error'] == 'session') {
                            info.modulo = 'global'
                        }
                        jAlert(getMsg(info.modulo, rta['error']), info.empresa, function () {
                            if (rta['error'] == 'session') {
                                location.reload();
                            }
                        });
                    } else {
                        if ($.isFunction(info.adicional)) {
                            info.adicional(rta);
                        }
                        notifica_ok(info.msgExito);
                    }
                }
            });
        }
    });

}


function coloca_boton(dt) {
    var datos_normales = {
        elem: '',
        title: '',
        caption: '',
        id: "",
        onClickButton: null,
        buttonicon: 'ui-btn-edit',
    }

    var p = $.extend(datos_normales, dt)
    var band = true;
    if (p.elem.indexOf("#") !== 0) {
        p.elem = "#" + p.elem;
    }
    if ($(p.elem).length <= 0) {
        return false
    }

    findnav = $(".navtable", p.elem)[0];

    if (!findnav) {
        $(p.elem).append('<table class="ui-pg-table"  border="0" cellspacing="0" cellpadding="0" style="width: 100%; table-layout: fixed; height: 100%;"><tr><td><table class="ui-pg-table navtable" align="left"><tr></tr></table><div style="float:right; margin-top:2px; margin-right:2px" align=\"center\" id="help' + p.elem.substring(2) + '" data-icon="help"></div></td></tr></table>')
        findnav = $(".navtable", p.elem)[0];
        band = false
    }
    if (band) {
        $("#" + p.elem.substring(3, p.elem.length)).navSeparatorAdd(p.elem);
    }
    var tbd = $("<td></td>");
    if (p.id) {
        $(tbd).attr("id", p.id);
    }

    if (p.buttonicon.toString().toUpperCase() == "NONE") {
        $(tbd).addClass('ui-pg-button ui-corner-all opera').append("<div class='ui-pg-div'>" + p.caption + "</div>");
    } else {
        cp = p.caption == "" ? "" : "&nbsp;<i>" + p.caption + "</i>";
        $(tbd).addClass('ui-pg-button ui-corner-all opera').append("<div class='ui-pg-div'><span class='ui-icon " + p.buttonicon + "'></span>" + cp + "</div>");
    }
    //$(tbd).addClass('ui-pg-button ui-corner-all').append("<div class='ui-pg-div'><a href='#' class='ui-icon "+p.buttonicon+"'></a>"+p.caption+"</div>");

    $("tr", findnav).append(tbd);

    $(tbd, findnav).attr("title", p.title || "").click(function (e) {
        e.preventDefault();
        if (!$(this).hasClass('ui-state-disabled')) {

            if ($.isFunction(p.onClickButton)) {
                p.onClickButton.call(e);
            }
        }
        return false;
    }).hover(function () {
        if (!$(this).hasClass('ui-state-disabled')) {
            $(this).addClass('ui-state-hover');
        }
    },
            function () {
                $(this).removeClass("ui-state-hover");
            }
    );
}

function newBottonGrid(grilla, opc) {
    var datos_normales = {
        pag: '',
        title: '',
        caption: '',
        id: "",
        onClickButton: null,
        posicion: "last",
        buttonicon: 'ui-btn-edit',
    }

    var p = $.extend(datos_normales, opc);

    grilla.navButtonAdd(p.pag, {
        id: p.id,
        caption: p.caption,
        buttonicon: p.buttonicon,
        title: p.title,
        onClickButton: p.onClickButton,
        position: p.posicion,
    });

}
