/* global $  */

var page_user = {
    loaded: false,
    baseUrl: "https://retenciones.mercadolibre.com.ve/mlretenciones",
    on_load: function(){
        if(!page_user.loaded){
            if (global.on_load()){
                page_user.grid.construction();
                page_user.loaded = true;
            }
            var obj;
            obj = document.getElementById("frm_save").addEventListener("click", page_user.form.savefrm);
        }
    },
    grid: {
        format: {
            column: {
                errshw: function(value,row,index){
                    var salida = "";
                    if (parseInt(row.status) !== 0){
                        salida = {class:'archiveShow'};
                    }else{
                        salida = {class:'errorShow'};
                    }
                    return salida;
                 },
            }
        },
        errShow: function(i){
            var row = $("#grid_area").datagrid('getRows')[i];
            var titulo = "";
            var msg = "";
            var header = "";

if (msg.length){
    msg = "<ul><li>" + msg.replace(/\|/g, "</li><li>") + "</li></ul>";
    $.messager.alert(titulo, header + msg);
}
        },
        construction: function(){
            var sessid=$("#sessid").html();
            var userid=$("#userid").html();
            var getlist="api/cruduser/getlist.php?sessid="+sessid+"&userid="+userid;
            var anchoCol = parseInt(window.innerWidth*0.95/6);
            // la altura debe hacerse antes de inyectar el codigo del grid
            $("#grid_area").css("height", $(".grid_area").height()+"px");
            
            /*#invoices"*/
            $("#grid_area").datagrid({
                url: getlist,
                /*width: (window.innerWidth*0.95)+"px",*/
                striped: true,
                fitColumns: true,
                autoRowHeight: true,
                singleSelect: true,
                loadMsg: "Cargando Información...",
                emptyMsg: "No hay información, incluya un usuario",
                showHeader: true,
                showFooter: true,
                pagination: true,
                pageSize: 20,
                idField: "id",
                columns:[
                    [
                    {width: anchoCol*0, align:"left", halign:"left",    field:"status", title:"ST", hidden:true},
                    {width: anchoCol*0, align:"left", halign:"left",    field:"id",     title:"ID", hidden:true},
                    {width: anchoCol/2, align:"left", halign:"center",  field:"errshw", title:"",       styler:page_user.grid.format.column.errshw},
                    {width: anchoCol*1, align:"left", halign:"left",    field:"user",   title:"Usr ID", sortable:true,},
                    {width: anchoCol*2, align:"left", halign:"left",    field:"name",   title:"Nombre", sortable:true,},
                    {width: anchoCol*2, align:"left", halign:"left",    field:"email",  title:"eMail",  sortable:true,}
                    ]
                ],
                toolbar: [{
                            iconCls: 'icon-add',
                            text: 'Incluir',
                            handler: page_user.form.add
                         },'-', {
                            iconCls: 'icon-edit',
                            text: 'Editar',
                            handler: page_user.form.edit
                         },'-',{
                            iconCls: 'icon-remove',
                            text: 'Eliminar',
                            handler: page_user.form.del
                }],
                onLoadSuccess: function(){
                    $("#datagrid-td-group1-0-1").css("background-color", "#dfdfdf");
                    $("#datagrid-td-group1-0-2").css("background-color", "#555");
                    // incluir search box
                    var html = '<div id="buscarCont" style="width:400px;position:absolute;top:3px;right:3px;text-align:right;">' +
                               '<input id="buscar" style="width:300px"></input>' +
                               '    <div id="menuBuscar" style="width:100px">' +
                               '        <div data-options="name:\'all\'">Todo</div>' +
                               '        <div data-options="name:\'user\'">Usr ID</div>' +
                               '        <div data-options="name:\'name\'">Nombre</div>' +
                               '        <div data-options="name:\'email\'">eMail</div>' +
                               '    </div>' +
                               '</div>';
                    $("#buscarCont").remove();
                    $(".datagrid-toolbar").append(html);
                    $("#buscar").searchbox({
                        prompt:'Buscar...',
                        searcher: function(value, name){
                            page_user.grid.searchField = name;
                            page_user.grid.searchValue = value;
                            $('#grid_area').datagrid('load', {
                                name: name,
                                value: value
                            });
                            //alert(value + " - " + name);
                        },
                        menu: "#menuBuscar"
                    });
                    $("#buscar").searchbox("selectName",page_user.grid.searchField);
                    $("#buscar").searchbox("setValue",page_user.grid.searchValue);
                },
                onLoadError: function(e){
                    //console.log(e);
                    $.messager.alert("Ocurrió un error al recuperar los datos", e.responseJSON.msg); 
                },
            });
            
            page_user.form.construction();
        }
    },
    form: {
        status: 0,
        construction: function(){

            $("#userid").textbox({
                label: 'User ID:',
                labelPosition: 'top',
                required:true,
                missingMessage: 'Código de usuario',
                width: 150
            });
            $("#status").switchbutton({
                width : 100,
                onText: "Activo",
                offText: "Inactivo",
                onChange: function(checked){
                }
            });
            $("#name").textbox({
                label:'Nombre',
                labelPosition:'top',
                required:true,
                missingMessage: 'Nombre del usuario',
                width: 325
            });
            $("#email").textbox({
                label:'Correo electrónico',
                labelPosition:'top',
                required:true,
                missingMessage: 'Correo electrónico',
                width: 325
            });
            $("#status").switchbutton({
                width : 100,
                onText: "Activo",
                offText: "Inactivo",
                onChange: function(checked){
                }
            });
            $("#accs_customers").switchbutton({
                width : 100,
                onText: "Si",
                offText: "No",
                onChange: function(checked){
                }
            });
            $("#accs_invoices").switchbutton({
                width : 100,
                onText: "Si",
                offText: "No",
                onChange: function(checked){
                }
            });
            $("#accs_approve").switchbutton({
                width : 100,
                onText: "Si",
                offText: "No",
                onChange: function(checked){
                }
            });
            $("#accs_refuse").switchbutton({
                width : 100,
                onText: "Si",
                offText: "No",
                onChange: function(checked){
                }
            });
            $("#accs_reports").switchbutton({
                width : 100,
                onText: "Si",
                offText: "No",
                onChange: function(checked){
                }
            });
            $("#accs_users").switchbutton({
                width : 100,
                onText: "Si",
                offText: "No",
                onChange: function(checked){
                }
            });

            $('#progressdlg').dialog({
                title: "Guardando",
                closed: true,
                modal: true,
                border: 'thin'
            });
            $('#dlg').dialog({
                closed: true,
                modal: true,
                border: 'thin'
            
            });
            
            $('#fm').form({
                iframe: false,
                width: 345,
            });
            
            // BOTONES
            $("#frm_save").linkbutton({
                width: 325
                /*iconCls: "icon-ok"*/
            });
            
            
        },
        edit: function(){
            var row = $('#grid_area').datagrid('getSelected');
            var sessid = $("#sessid").html();

            if (row){
                var parameterAjax = {   metodo      : "GET",
                                        url         : global.baseUrl + "/cruduser/getentry.php",  
                                        parameters  : "?sessid="+sessid+"&id="+row.id,
                                        onsucces    : function(json){   
                                                                        var rs = JSON.parse(json);
                                                                        if(rs.rsp){
                                                                            if (rs){
                                                                                page_user.form.status = row.status;
                                                                                $('#dlg').dialog('open').dialog('center').dialog('setTitle','Edición de Usuario');
                                                                                $('#fm').form('load',rs);
                                                                            }
                                                                        }else{ //console.log(json.msg);
                                                                            var msg = json.msg;
                                                                            $.messager.alert('Error al cargar el usuario N°'+ row.documentid, msg); 
                                                                        }
                                                                    },
                                        onerror     : function(json){   //console.log(json);
                                                                        json = JSON.parse(json);
                                                                        var msg = "";
                                                                        if(json.rsp){
                                                                            msg = json.msg;
                                                                            $.messager.alert('Error al cargar el usuario N°'+ row.documentid, msg); 
                                                                        }
                                                                    } 
                                    };
                global.utils.callAjax( parameterAjax);
                
            }else{
                $.messager.alert("Para Editar", "Selecciona algún usuario antes de editar");
            }
        },
        add: function(){
            var sessid = $("#sessid").html();
            $('#dlg').dialog('open').dialog('center').dialog('setTitle','Nuevo Usuario');
            $('#fm').form('clear');
            $('#grid_area').datagrid('clearSelections');
            $('#userid').next().find('input').focus();
        },
        del: function(){
            var row = $('#grid_area').datagrid('getSelected');
            var sessid = $("#sessid").html();
            if (row){
                $.messager.confirm( 'Confirme el borrado',
                    '¿Estás seguro de querer eliminar este registro?',
                    function(r){ 
                        if (r){
                            var parameterAjax = {   metodo      : "GET",
                                                     url         : global.baseUrl + "/cruduser/delete.php",  
                                                     parameters  : "?sessid="+sessid+"&id="+row.id,
                                                     onsucces    : function(json){   
                                                                                     $('#grid_area').datagrid('reload');
                                                                                 },
                                                     onerror     : function(json){   
                                                                                     json = JSON.parse(json);
                                                                                     var msg = "";
                                                                                     if(!json.rsp){
                                                                                         msg = json.msg;
                                                                                         $.messager.alert('Error al eliminar el usuario N°'+ row.custid, msg); 
                                                                                     }
                                                                                 } 
                                                 };
                            global.utils.callAjax( parameterAjax);
                        }
                    });
            }else{
                $.messager.alert("Para Borrar", "Selecciona algún usuario antes de borrar");
            }
        },
        close: function(){
            $('#dlg').dialog('close')
        },
        savefrm: function(){
            // prevenir cuando está deshabilitado

            //if (page_user.form.status !==0) return;
            var id;
            var row = $('#grid_area').datagrid('getSelected');
            if(!row){ id = 0;}else{ id = row.id}
//console.log(global.baseUrl + "/cruduser/update.php"+"?sessid="+$("#sessid").html()+"&id="+id)
            $('#fm').form('submit',{
                enctype: "multipart/form-data",
                url: global.baseUrl + "/cruduser/update.php"+
                     "?sessid="+$("#sessid").html()+
                     "&id="+id,
                onProgress: function(percent) {
                    $('#progressbar').progressbar("setValue",percent);
                },
                onSubmit: function(){ 
                    if ($(this).form('validate')){
                        $('#progressdlg').dialog('open');
                        $('#progressbar').progressbar("setValue",0);
                        return(true);
                    }else{
                        $.messager.alert("Completa la Información", "Hay campos requeridos que no se están completando");
                        return(false);
                    }
                },
                success:  function(result){
                    $('#progressdlg').dialog('close');
                    var jsonresp;
                    if (global.utils.isJSON(result)){
                        jsonresp = JSON.parse(result);
                    }else{
                        jsonresp = {
                                    rsp: false,
                                    errno: 99,
                                    msg: result
                        }
                    }

                    if (!jsonresp.rsp){
                        $.messager.show({ title: 'Error:'+jsonresp.errno, msg: jsonresp.msg});
                    }else{
                        if (jsonresp.errlvl == 1){
                            $.messager.alert("Guardado con Advertencias", "Se ha guardado la información pero se han reportado algunas advertencias.");
                        }
                        if (jsonresp.errlvl == 2){
                            $.messager.alert("Guardado con Errores", "Se ha guardado la información pero no será procesado hasta que atienda los errores ocurridos.");
                        }

                        $('#dlg').dialog('close');
                        $('#grid_area').datagrid('reload');
                    }
                }
            });
        },
    }
};
page_user.on_load();