/* global $  */

var page_docs = {
    loaded: false,
    baseUrl: "https://retenciones.mercadolibre.com.ve/mlretenciones",
    //baseUrl: "https://vpskromasys2.hostnetcom.com/~mlretenciones",
    on_load: function(){
        if(!page_docs.loaded){
            if (global.on_load()){
                page_docs.grid.construction();
                page_docs.loaded = true;                
            }
        }
    },
    filter: {
        filtro: {pending:true,aproved:true,warning:true,ready:true},
        construction: function(){
            $('#showinfo').dialog({
                title: 'Filtrar',
                width: window.innerWidth*0.50,
                height: window.innerHeight*0.50,
                closed: true,
                modal: true
            });
            var html = '';
            html += '<form id="filter">';

            html += '<div class="filtConTable" style="height:90%">';
            html +=   '<div class="filtConCell">';
            html +=     '<div class="filtLbl">Estatus</div>';
            html +=     '<div class="filtCell filtEstatus">';
            html +=       '<input id="pending" name="pending">';
            html +=     '</div>';
            html +=     '<div class="filtCell filtEstatus">';
            html +=       '<input id="aproved" name="aproved">';
            html +=     '</div>';
            html +=     '<div class="filtCell filtEstatus">';
            html +=       '<input id="warning" name="warning">';
            html +=     '</div>';
            html +=     '<div class="filtCell filtEstatus">';
            html +=       '<input id="ready" name="ready">';
            html +=     '</div>';
            html +=   '</div>';
            html +=   '<div class="filtConCell">';
            html +=     '<div class="filtLbl">Fechas de Facturas</div>';
            html +=     '<div class="filtCell filtFecha">';
            html +=       '<input id="fDesde" name="fDesde">';
            html +=     '</div>';
            html +=     '<div class="filtCell filtFecha">';
            html +=       '<input id="fHasta" name="fHasta">';
            html +=     '</div>';
            html +=     '<div class="filtLbl">Fechas de Reportadas</div>';
            html +=     '<div class="filtCell filtFecha">';
            html +=       '<input id="rDesde" name="rDesde">';
            html +=     '</div>';
            html +=     '<div class="filtCell filtFecha">';
            html +=       '<input id="rHasta" name="rHasta">';
            html +=     '</div>';
            html +=   '</div>';
            html += '</div>';
            
            // botones
            html += '<div class="filtConTable" style="height:10%">';
            html +=   '<div class="filtConCell filtBtnCell">';
            html +=     '<a id="frm_filtrar" name="frm_filtrar"></a>';
            html +=   '</div>';
            html +=   '<div class="filtConCell filtBtnCell">';
            html +=     '<a id="frm_limpiar" name="frm_limpiar"></a>';
            html +=   '</div>';
            html += '</div>';
            
            html += '</form>';
            
            $('#showinfo').html(html);
            
            $("#pending").checkbox({
                label: 'Pendientes',
                labelWidth: 100,
                labelPosition: 'left',
                checked: page_docs.filter.filtro.pending,
                value: "yes"
            });
            $("#aproved").checkbox({
                label: 'Aprobadas',
                labelWidth: 100,
                labelPosition: 'left',
                checked: page_docs.filter.filtro.aproved,
                value: "yes"
            });
            $("#warning").checkbox({
                label: 'Advertencias',
                labelWidth: 100,
                labelPosition: 'left',
                checked: page_docs.filter.filtro.warning,
                value: "yes"
            });
            $("#ready").checkbox({
                label: 'Reportadas',
                labelWidth: 100,
                labelPosition: 'left',
                checked: page_docs.filter.filtro.ready,
                value: "yes"
            });
            
            $("#fDesde").datebox({
                label: 'Desde',
                labelPosition: 'left',
                value: page_docs.filter.filtro.fDesde,
                formatter: function(date){
                    var y = date.getFullYear();
                    var m = date.getMonth()+1;
                    var d = date.getDate();
                    return (d<10?('0'+d):d) + '/' + (m<10?('0'+m):m) + '/' + y;
                },
                parser: function(s){
                    if (!s) return new Date();
                    var ss = (s.split('/'));
                    var d = parseInt(ss[0],10);
                    var m = parseInt(ss[1],10);
                    var y = parseInt(ss[2],10);
                    if (!isNaN(y) && !isNaN(m) && !isNaN(d)){
                        return new Date(y,m-1,d);
                    } else {
                        return new Date();
                    }
                }
            });
            $("#fHasta").datebox({
                label: 'Hasta',
                labelPosition: 'left',
                value: page_docs.filter.filtro.fHasta,
                formatter: function(date){
                    var y = date.getFullYear();
                    var m = date.getMonth()+1;
                    var d = date.getDate();
                    return (d<10?('0'+d):d) + '/' + (m<10?('0'+m):m) + '/' + y;
                },
                parser: function(s){
                    if (!s) return new Date();
                    var ss = (s.split('/'));
                    var d = parseInt(ss[0],10);
                    var m = parseInt(ss[1],10);
                    var y = parseInt(ss[2],10);
                    if (!isNaN(y) && !isNaN(m) && !isNaN(d)){
                        return new Date(y,m-1,d);
                    } else {
                        return new Date();
                    }
                }
            });
            $("#rDesde").datebox({
                label: 'Desde',
                labelPosition: 'left',
                value: page_docs.filter.filtro.rDesde,
                formatter: function(date){
                    var y = date.getFullYear();
                    var m = date.getMonth()+1;
                    var d = date.getDate();
                    return (d<10?('0'+d):d) + '/' + (m<10?('0'+m):m) + '/' + y;
                },
                parser: function(s){
                    if (!s) return new Date();
                    var ss = (s.split('/'));
                    var d = parseInt(ss[0],10);
                    var m = parseInt(ss[1],10);
                    var y = parseInt(ss[2],10);
                    if (!isNaN(y) && !isNaN(m) && !isNaN(d)){
                        return new Date(y,m-1,d);
                    } else {
                        return new Date();
                    }
                }
            });
            $("#rHasta").datebox({
                label: 'Hasta',
                labelPosition: 'left',
                value: page_docs.filter.filtro.rHasta,
                formatter: function(date){
                    var y = date.getFullYear();
                    var m = date.getMonth()+1;
                    var d = date.getDate();
                    return (d<10?('0'+d):d) + '/' + (m<10?('0'+m):m) + '/' + y;
                },
                parser: function(s){
                    if (!s) return new Date();
                    var ss = (s.split('/'));
                    var d = parseInt(ss[0],10);
                    var m = parseInt(ss[1],10);
                    var y = parseInt(ss[2],10);
                    if (!isNaN(y) && !isNaN(m) && !isNaN(d)){
                        return new Date(y,m-1,d);
                    } else {
                        return new Date();
                    }
                }
            });
            
            // BOTONES
            $("#frm_filtrar").linkbutton({
                text: "Filtrar"
            });
            $("#frm_filtrar").bind("click", page_docs.filter.apply);
            $("#frm_limpiar").linkbutton({
                text: "Limpiar"
            });
            $("#frm_limpiar").bind("click", page_docs.filter.remove);
            
            $('#showinfo').dialog('open'); //.dialog('setTitle','Rechazo de facturas');
        },
        apply: function(){
            page_docs.filter.filtro = {};
            if ($("#fDesde").val() !== "") {
                page_docs.filter.filtro.fDesde = $("#fDesde").val();
            }
            if ($("#fHasta").val() !== ""){
                page_docs.filter.filtro.fHasta = $("#fHasta").val();
            }
            if ($("#rDesde").val() !== "" ){
                page_docs.filter.filtro.rDesde = $("#rDesde").val();
            }
            if ($("#rHasta").val() !== ""){
                page_docs.filter.filtro.rHasta = $("#rHasta").val();
            }
            page_docs.filter.filtro.pending = $("#pending").checkbox("options").checked;
            page_docs.filter.filtro.aproved = $("#aproved").checkbox("options").checked;
            page_docs.filter.filtro.warning = $("#warning").checkbox("options").checked;
            page_docs.filter.filtro.ready = $("#ready").checkbox("options").checked;
            page_docs.filter.filtro.value = page_docs.grid.search.value;
            page_docs.filter.filtro.field = page_docs.grid.search.field;
            page_docs.grid.search = page_docs.filter.filtro;
            
            // poner azul el boton a los coñazos
            $(".datagrid-toolbar td:contains('Filtro')").css("background-color", "cornflowerblue");
            
            $('#grid_area').datagrid('load', page_docs.grid.search);
            
            $("#buscar").searchbox("selectName",page_docs.grid.search.field);
            $("#buscar").searchbox("setValue",page_docs.grid.search.value);
            
            $('#showinfo').dialog('close');
        },
        remove: function(){
            page_docs.filter.filtro = {pending:true,aproved:true,warning:true,ready:true};
            page_docs.filter.filtro.value = page_docs.grid.search.value;
            page_docs.filter.filtro.field = page_docs.grid.search.field;
            page_docs.grid.search = page_docs.filter.filtro;
            
            // quitar el azul el boton a los coñazos
            $(".datagrid-toolbar td:contains('Filtro')").css("background-color", "");
            
            $('#grid_area').datagrid('load', page_docs.grid.search);
            $("#buscar").searchbox("selectName",page_docs.grid.search.field);
            $("#buscar").searchbox("setValue",page_docs.grid.search.value);
            $('#showinfo').dialog('close');
        },
    },
    grid: {
        search: {field: "Todos", value: ""},
        showTip: {
            errshw: function(i){
                var row = $("#grid_area").datagrid('getRows')[i];
                var msg = "";
                
                if (row.reported){
                    msg = "Documento Reportado <br/> el " + row.reportedat;
                    
                }else{
                    if (row.aproved){
                        msg = "Documento Aprobado";
                    }else{
                        switch (parseInt(row.status)){
                            case 1:
                            case 2:
                                msg = "<ul><li>"+row.errdsc.slice(0,-1).replace(/\|/g, "</li><li>")+"</li></ul>";
                                break;
                        }
                    }
                }
                
                if (msg.length){
                    var html = "";
                    //borrar busbuja anterior si existe
                    $(".infoTip").remove();
                    // posicionar burbuja
                    var lineas = (msg.match(/<li>/g) || []).length;
                    var o = $("[field=errshw]")[0];
                    var left = o.offsetLeft + o.offsetWidth + 30;
                    var top = $(".datagrid-btable").position().top + o.offsetHeight * (i) + 160 - (8*lineas);
                    html += '<div class="infoTip infoTipArrowLeft" style="top:'+top+'px;left:'+left+'px">';
                    html += '<div class="infoTipClose">';
                    html += '<span onclick="$(\'.infoTip\').remove()"><i class="fas fa-times"></i></span>';
                    html += '</div>';
                    html += '<div class="infoTipCont">';
                    html += '<div class="infoTipRow">';
                    html += '<div class="infoTipMsg">'+msg+'</div>';
                    html += '</div>';
                    html += '</div>';
        
                    html += '</div>';
                    html += '</div>';
                    
                    $("#showTip").html(html);
                    setTimeout(function(){$(".infoTip").css({opacity:1})},200);
                }
            },
            custid: function(i){
                var estado;
                var row = $("#grid_area").datagrid('getRows')[i];
                if (row){
                    if (row.custstatus == 1){ estado = "Activo"}else{ estado = "Bloqueado"}
                    var html = "";
                    //borrar busbuja anterior si existe
                    $(".infoTip").remove();
                    // posicionar burbuja
                    var o = $("[field=custid]")[0];
                    var left = o.offsetLeft + o.offsetWidth + 4;
                    var top = $(".datagrid-btable").position().top + o.offsetHeight * (i) + 150 - 8;
                    html += '<div class="infoTip infoTipArrowLeft" style="top:'+top+'px;left:'+left+'px">';
                    html += '<div class="infoTipClose">';
                    html += '<span onclick="$(\'.infoTip\').remove()"><i class="fas fa-times"></i></span>';
                    html += '</div>';
                    html += '<div class="infoTipCont">';
                    html += '<div class="infoTipRow">';
                    html += '<div class="infoTipLbl">Estado</div>';
                    html += '<div style="text-align:right" class="infoTipVal">'+estado+'</div>';
                    html += '</div>';
                    html += '<div class="infoTipRow">';
                    html += '<div class="infoTipLbl">RIF</div>';
                    html += '<div style="text-align:right" class="infoTipVal">'+row.rif+'</div>';
                    html += '</div>';
                    html += '<div class="infoTipRow">';
                    html += '<div class="infoTipLbl">Razon S.</div>';
                    html += '<div style="text-align:right" class="infoTipVal">'+row.name+'</div>';
                    html += '</div>';
                    html += '<div class="infoTipRow">';
                    html += '<div class="infoTipLbl">Alias</div>';
                    html += '<div style="text-align:right" class="infoTipVal">'+row.nickname+'</div>';
                    html += '</div>';
    
                    html += '</div>';
                    html += '</div>';
                    
                    $("#showTip").html(html);
                    setTimeout(function(){$(".infoTip").css({opacity:1})},200);
                }
            },
            factura: function(i){
                //window.open(page_docs.baseUrl + url, "_blank", "width=400,height=500");
                var row = $("#grid_area").datagrid('getRows')[i];
                if (row){
                    var html = "";
                    //borrar busbuja anterior si existe
                    $(".infoTip").remove();
                    // posicionar burbuja
                    var o = $("[field=docnumber]")[0];
                    var left = o.offsetLeft + o.offsetWidth + 4;
                    var top = $(".datagrid-btable").position().top + o.offsetHeight * (i) + 150 - 8;
                    html += '<div class="infoTip infoTipArrowLeft" style="top:'+top+'px;left:'+left+'px">';
                    html += '<div class="infoTipClose">';
                    html += '<span onclick="$(\'.infoTip\').remove()"><i class="fas fa-times"></i></span>';
                    html += '</div>';
                    html += '<div class="infoTipCont">';
                    html += '<div class="infoTipRow">';
                    html += '<div class="infoTipLbl">Control</div>';
                    html += '<div style="text-align:right" class="infoTipVal">'+row.doccontrol+'</div>';
                    html += '</div>';
                    html += '<div class="infoTipRow">';
                    html += '<div class="infoTipLbl">Base</div>';
                    html += '<div style="text-align:right" class="infoTipVal">'+row.base+'</div>';
                    html += '</div>';
                    html += '<div class="infoTipRow">';
                    html += '<div class="infoTipLbl">Total</div>';
                    html += '<div style="text-align:right" class="infoTipVal">'+row.total+'</div>';
                    html += '</div>';
    
                    html += '</div>';
                    html += '</div>';
                    
                    $("#showTip").html(html);
                    setTimeout(function(){$(".infoTip").css({opacity:1})},200);
                }     
            },
            retISLR: function(i){
                //window.open(page_docs.baseUrl + url, "_blank", "width=400,height=500");
                var row = $("#grid_area").datagrid('getRows')[i];
    
                if (row && row.islrnumber){
                    var html = "";
                    //var tasa = (parseFloat(row.islramount*100/row.base));
                    var tasa = parseFloat(row.islramount.replace(/\./g,"").replace(/\,/g,"."))*100/parseFloat(row.base.replace(/\./g,"").replace(/\,/g,"."));
                    tasa = tasa.toFixed(2);
                
                    //borrar busbuja anterior si existe
                    $(".infoTip").remove();
                    // posicionar burbuja
                    var o = $("[field=islrnumber]")[0];
                    var left = o.offsetLeft - 160;
                    var top = $(".datagrid-btable").position().top + o.offsetHeight * (i) + 150 - 30;
                    html += '<div class="infoTip infoTipArrowRight" style="top:'+top+'px;left:'+left+'px">';
                    html += '<div class="infoTipClose">';
                    html += '<span onclick="$(\'.infoTip\').remove()"><i class="fas fa-times"></i></span>';
                    html += '</div>';
                    html += '<div class="infoTipCont">';
                    html += '<div class="infoTipRow">';
                    html += '<div class="infoTipLbl">Fecha</div>';
                    html += '<div style="text-align:right" class="infoTipVal">'+row.islrdate+'</div>';
                    html += '</div>';
                    html += '<div class="infoTipRow">';
                    html += '<div class="infoTipLbl">Total</div>';
                    html += '<div style="text-align:right" class="infoTipVal">'+row.total+'</div>';
                    html += '</div>';
                    html += '<div class="infoTipRow">';
                    html += '<div class="infoTipLbl">Base I.</div>';
                    html += '<div style="text-align:right" class="infoTipVal">'+row.base+'</div>';
                    html += '</div>';
                    html += '<div class="infoTipRow">';
                    html += '<div class="infoTipLbl">% Aplicado</div>';
                    html += '<div style="text-align:right" class="infoTipVal">'+tasa+'</div>';
                    html += '</div>';
                    html += '<div class="infoTipRow">';
                    html += '<div class="infoTipLbl">Mto. Ret.</div>';
                    html += '<div style="text-align:right" class="infoTipVal">'+row.islramount+'</div>';
                    html += '</div>';
    
                    html += '</div>';
                    html += '</div>';
                    
                    $("#showTip").html(html);
                    setTimeout(function(){$(".infoTip").css({opacity:1})},200);
                }                
            },
            retIVA: function(i){
                //window.open(page_docs.baseUrl + url, "_blank", "width=400,height=500");
                var ancho = (screen.width*.95)*.25;
                var row = $("#grid_area").datagrid('getRows')[i];
                if (row&& row.ivanumber){
                    var html = "";
                    //var tasa = (parseFloat(row.islramount*100/row.base));
                    var tasa = parseFloat(row.ivaamount.replace(/\./g,"").replace(/\,/g,"."))*100/parseFloat(row.base.replace(/\./g,"").replace(/\,/g,"."));
                    
                    var totfac = parseFloat(row.total.replace(/\./g,"").replace(/\,/g,"."));
                    var base = parseFloat(row.base.replace(/\./g,"").replace(/\,/g,"."));
                    var iva = totfac-base;
                    var montoret = row.ivaamount.replace(/\./g,"").replace(/\,/g,".");
                    tasa = montoret/iva*100;
                    tasa = tasa.toFixed(2);
                
                    //borrar busbuja anterior si existe
                    $(".infoTip").remove();
                    // posicionar burbuja
                    var o = $("[field=ivanumber]")[0];
                    var left = o.offsetLeft - 160;
                    var top = $(".datagrid-btable").position().top + o.offsetHeight * (i) + 150 - 30;
                    html += '<div class="infoTip infoTipArrowRight" style="top:'+top+'px;left:'+left+'px">';
                    html += '<div class="infoTipClose">';
                    html += '<span onclick="$(\'.infoTip\').remove()"><i class="fas fa-times"></i></span>';
                    html += '</div>';
                    html += '<div class="infoTipCont">';
                    html += '<div class="infoTipRow">';
                    html += '<div class="infoTipLbl">Fecha</div>';
                    html += '<div style="text-align:right" class="infoTipVal">'+row.ivadate+'</div>';
                    html += '</div>';
                    html += '<div class="infoTipRow">';
                    html += '<div class="infoTipLbl">Total</div>';
                    html += '<div style="text-align:right" class="infoTipVal">'+row.total+'</div>';
                    html += '</div>';
                    html += '<div class="infoTipRow">';
                    html += '<div class="infoTipLbl">Base I.</div>';
                    html += '<div style="text-align:right" class="infoTipVal">'+row.base+'</div>';
                    html += '</div>';
                    html += '<div class="infoTipRow">';
                    html += '<div class="infoTipLbl">% Aplicado</div>';
                    html += '<div style="text-align:right" class="infoTipVal">'+tasa+'</div>';
                    html += '</div>';
                    html += '<div class="infoTipRow">';
                    html += '<div class="infoTipLbl">Mto. Ret.</div>';
                    html += '<div style="text-align:right" class="infoTipVal">'+row.ivaamount+'</div>';
                    html += '</div>';
    
                    html += '</div>';
                    html += '</div>';
                    
                    $("#showTip").html(html);
                    setTimeout(function(){$(".infoTip").css({opacity:1})},200);
                }
            },
            pdf: function(url){
                var ancho = window.innerWidth*.35;
                var alto = window.innerHeight*.9;
                //window.open(page_docs.baseUrl + url, "_blank", "width="+ancho+",height="+alto+",top=10,left="+(window.innerWidth-ancho-40));
                var sessionid = $("#sessid").html();;
                var dir;
                if (url.indexOf("islr")>=0)
                    dir = "islr";
                else
                    dir = "iva";
                var ref = url.replace(/^.*[\\\/]/, '').split(".")[0];
                var pag = page_docs.baseUrl + "/cms/api/showpdf.php";
                pag += "?sessionid=" + sessionid;
                pag += "&dir=" + dir;
                pag += "&ref=" + ref;
                window.open(pag, "_blank", "width="+ancho+",height="+alto+",top=10,left="+(window.innerWidth-ancho-40));
            },
            islrPdf: function(i){
                var row = $("#grid_area").datagrid('getRows')[i];
                if (row.islrpdf){
                    page_docs.grid.showTip.pdf(row.islrpdf);
                }else{
                    //$.messager.alert("Comprobante del ISLR", "No existe registro del archivo","info");
                }
            },
            ivaPdf: function(i){
                var row = $("#grid_area").datagrid('getRows')[i];
                if (row.ivapdf){
                    page_docs.grid.showTip.pdf(row.ivapdf);
                }else{
                    //$.messager.alert("Comprobante del IVA", "No existe registro del archivo","info");
                }
            },
            ivaCheck: function(i){
            }
        },
        format: {
            column: {
                errshw: function(value,row,index){
                    var salida = {};
                    switch (row.st){
                        case "REP":
                            salida = {class:"stReported"};
                            break;
                        case "APR":
                            salida = {class:'stAproved'};
                            break;
                        case "OK":
                            salida = {class:'stOK'};
                            break;
                        case "WAR":
                            salida = {class:'stWarning'};
                            break;
                        default:
                            salida = {class:'stError'};
                            break;
                    }
                    return salida;
                 },
                datashw: function(value,row,index){
                    var salida = "";
                    if (value){
                        salida = {class:'dataShow'};
                    }
                    return salida;
                },
                pdfshwislr:function(value,row,index){
                    var salida = "";
                    if (row.islrpdf === "" || row.islrpdf === null){
                        salida = ""; //{class:'nullShow'};
                    }else{
                        salida = {class:'pdfShow'};
                    }
                    return salida;
                },
                pdfshwiva:function(value,row,index){
                    var salida = "";
                    if (row.ivapdf === "" || row.ivapdf === null){
                        salida = ""; //{class:'nullShow'};

                    }else{
                        salida = {class:'pdfShow'};
                    }
                    return salida;
                },
            }
        },
        buttons: {
            approve: function(){
                var row = $('#grid_area').datagrid('getChecked');
                var sessid  = $("#sessid").html();
                var accs    = $("#accs_a").html();
                // Se arma el parametro de los registros marcados
                var records = "";
                for (var item of row) { records += item.documentid + "|"; }
                records = records.slice(0,-1); // Se elimina el ultimo |
                
                if (accs == "."){
                    if (row.length){
                        $.messager.confirm( 'Confirme la aprobación',
                            '¿Estás seguro de querer aprobar los '+ row.length +' registros marcados?',
                            function(r){ 
                                if (r){
                                    var parameterAjax = {    metodo      : "GET",
                                                             url         : global.baseUrl + "/cruddocs/approve.php",  
                                                             parameters  : "?sessid="+sessid+"&records="+records,
                                                             onsucces    : function(json){  
                                                                                            if(JSON.parse(json).rsp){
                                                                                                $.messager.alert('Proceso de aprobación', JSON.parse(json).msg); 
                                                                                            }
                                                                                            $("#grid_area").datagrid("uncheckAll");
                                                                                            $('#grid_area').datagrid('reload');
                                                                                         },
                                                             onerror     : function(json){  
                                                                                            json = JSON.parse(json);
                                                                                            if(!json.rsp){
                                                                                                $.messager.alert('Error al Aprobar', json.msg); 
                                                                                            }
                                                                                         } 
                                                         };
                                    global.utils.callAjax( parameterAjax);
                                }
                            });
                    }else{
                        $.messager.alert("Para Aprobar", "Marca algún documento para ser aprobado");
                    }
                }else{
                    $.messager.alert("Para Aprobar", "No tienes privilegios para esta opción");
                }
            },
            reject: function(){
                var row = $('#grid_area').datagrid('getChecked');
                var sessid  = $("#sessid").html();
                var accs    = $("#accs_r").html();
                var records = "";
                for (var item of row) { records += item.documentid + "|"; }
                records = records.slice(0,-1); // Se elimina el ultimo |
                
                if (accs == "."){
                    if (row.length){
                        $.messager.prompt({
                            title:  "Motivo",
                            msg: "Indíque el motivo por el cual está rechazando las " + row.length + " facturas seleccionadas ",
                            fn: function (r){
                                if (r !== undefined)
                                    if (r.length){
                                        var parameterAjax = {   metodo      : "GET",
                                                                url         : global.baseUrl + "/cruddocs/reject.php",  
                                                                parameters  : "?sessid="+sessid+"&records="+records+"&msg="+r,
                                                                onsucces    : function(json){   
                                                                                                if(JSON.parse(json).rsp){
                                                                                                    $.messager.alert('Proceso de Rechazo', JSON.parse(json).msg); 
                                                                                                }
                                                                                                $("#grid_area").datagrid("uncheckAll");
                                                                                                $('#grid_area').datagrid('reload');
                                                                                             },
                                                                onerror     : function(json){   ////console.log(json);
                                                                                                if(!JSON.parse(json).rsp){
                                                                                                    $.messager.alert('Proceso de Rechazo', JSON.parse(json).msg); 
                                                                                                }
                                                                                             }
                                                             };
                                        global.utils.callAjax( parameterAjax);
                                    }else{
                                        $.messager.alert("Para Proceder", "Debes indicar un motivo para rechazar los documentos");
                                    }
                            }
                        });
                    }else{
                        $.messager.alert("Para Proceder", "Marca algún documento para ser rechazado");
                    }
                }else{
                    $.messager.alert("Para Rechazo", "No tienes privilegios para esta opción");        
                }
            },
            report: {
                
                reported: {},
                action: function(){
                    var accs    = $("#accs_p").html();
                    if (accs == "."){
                    
                    
                        var row = $('#grid_area').datagrid('getChecked');
            
                        if (row.length){
                            page_docs.grid.buttons.report.dateForm.construction();
                        }else{
                            $.messager.alert("Para Reportar", "Marca algún documento para emitir el informe");
                        }
                    }else{
                        $.messager.alert("Para Reportar", "No tienes privilegios para esta opción");
                    }
                },
                dateForm: {
                    construction: function(){
                        $('#showinfo').dialog({
                            title: 'Fecha y Hora del Reporte',
                            width: window.innerWidth*0.30,
                            height: window.innerHeight*0.30,
                            closed: true,
                            modal: true
                        });
                        var html = '';
                        html += '<form id="filter">';
                        html += '<div class="filtConTable" style="height:15%">';
                        html += '</div>';
                
                        html += '<div class="filtConTable" style="height:55%">';
                        html +=   '<div class="filtConCell">';
                        //html +=     '<div class="filtLbl">Fecha y Hora del Reporte</div>';
                        html +=     '<div class="filtCell filtFecha">';
                        html +=       '<input id="fReport" name="fReport">';
                        html +=     '</div>';
                        html +=   '</div>';
                        html += '</div>';
                        
                        // botones
                        html += '<div class="filtConTable" style="height:10%">';
                        html +=   '<div class="filtConCell filtBtnCell">';
                        html +=     '<a id="frm_reportar" name="frm_reportar"></a>';
                        html +=   '</div>';
                        html += '</div>';
                        
                        html += '</form>';
                        $('#showinfo').html(html);
                        
                        $("#fReport").datetimebox({
                            //label: 'Fecha y Hora del Reporte',
                            //labelPosition: 'left',
                            //width: '120',
                            showSeconds: false,
                            formatter: function(date){
                                var y  = date.getFullYear();
                                var m  = date.getMonth()+1;
                                var d  = date.getDate();
                                var h  = date.getHours();
                                var mi = date.getMinutes();
                                var s  = date.getSeconds();
                                return (d<10?('0'+d):d) +'/'+ (m<10?('0'+m):m) +'/'+ y +" "+ (h<10?('0'+h):h) +':'+ (mi<10?('0'+mi):mi) +":"+ (s<10?('0'+s):s) ;
                            },
                            parser: function(s){
                                if (!s) return new Date();
                                var datetime = (s.split(' '));
                                var ss = (datetime[0].split('/'));
                                var day = parseInt(ss[0],10);
                                var month = parseInt(ss[1],10);
                                var year = parseInt(ss[2],10);
                                    ss = (datetime[1].split(':'));
                                var hours   = parseInt(ss[0],10);
                                var minutes = parseInt(ss[1],10);
                                var seconds = parseInt(ss[2],10);
                                if (!isNaN(year) && !isNaN(month) && !isNaN(day) && !isNaN(hours) && !isNaN(minutes) && !isNaN(seconds)){
                                    return new Date(year, month-1, day, hours, minutes, seconds);
                                } else {
                                    return new Date();
                                }
                            }
                        });
                        
                        // Asignar Fecha actual
                        var d = new Date();
                        $("#fReport").datetimebox("setValue", d.getDate()+"/"+(d.getMonth()+1)+"/"+d.getFullYear()+" "+d.getHours()+":"+d.getMinutes());
                        
                        // BOTONES
                        $("#frm_reportar").linkbutton({
                            text: "Reportar"
                        });
                        $("#frm_reportar").bind("click", function(){
                            if ($("#fReport").val().length) {
                                $('#showinfo').dialog('close');
                                
                                var row = $('#grid_area').datagrid('getChecked');
                                var sessid  = $("#sessid").html();
                                // Se arma el parametro de los registros marcados
                                var records = "";
                                for (var item of row) { records += item.documentid + "|"; }
                                records = records.slice(0,-1); // Se elimina el ultimo |
                                
                                var ancho   = window.innerWidth*.35;
                                var alto    = window.innerHeight*.9;  
                                var parms   = "?sessid="+sessid+"&records="+records+"&fReport="+$("#fReport").val();
                                //window.open(page_docs.baseUrl + "/cms/api/cruddocs/report.php"+parms, "_blank", "width="+ancho+",height="+alto+",top=10,left="+(window.innerWidth-ancho-40));
                                ////console.log(parms);
                                window.open(page_docs.baseUrl + "/cms/api/cruddocs/report.php"+parms);
                                setTimeout(function(){$("#grid_area").datagrid("uncheckAll");
                                                      $('#grid_area').datagrid('reload');}, 2000);
                            }else{
                                $.messager.alert("Fecha Inválida", "Debe indicarse una fecha de reporte válida");
                            }
                        });
                        $('#showinfo').dialog('open'); 
                    }
                },
            },
        },
        construction: function(){
            var sessid=$("#sessid").html();
            var userid=$("#userid").html();
            var getlist="api/cruddocs/getlist.php?sessid="+sessid+"&userid="+userid;
            var anchoCol = parseInt(window.innerWidth*0.95/(12));
            
            // la altura debe hacerse antes de inyectar el codigo del grid
            $("#grid_area").css("height", $(".grid_area").height()+"px");
            
            $("#grid_area").datagrid({
                url: getlist,
                striped: true,
                fitColumns: false,
                autoRowHeight: true,
                singleSelect: false,
                checkOnSelect: false,
                selectOnCheck: false,
                loadMsg: "Cargando Información...",
                emptyMsg: "No hay información",
                showHeader: true,
                showFooter: true,
                pagination: true,
                pageSize: 20,
                remoteSort: true,
                remoteFilter: false,
                sortName: 'docdate',
                sortOrder: 'desc',
                idField: "documentid",
                columns:[
                    [
                    {title:"", halign:"center", colspan:6},
                    {title:"ISLR", halign:"center", colspan:3},
                    {title:"IVA", halign:"center", colspan:14},
                    ],
                    [
                    {width: anchoCol*0.50, align:"center", halign:"center", field:"mark",        title:"",            checkbox:true},    // http://jsfiddle.net/yHdnH/
                    {width: anchoCol*0.50, align:"center", halign:"center", field:"errshw",      title:"",            styler:page_docs.grid.format.column.errshw},
                    {width: anchoCol*1.00, align:"left",   halign:"left",   field:"custid",      title:"CustID",      sortable:true, styler:page_docs.grid.format.column.datashw},
                    {width: anchoCol*1.00, align:"left",   halign:"left",   field:"docnumber",   title:"Factura",     sortable:true, styler:page_docs.grid.format.column.datashw},
                    {width: anchoCol*0.75, align:"left",   halign:"left",   field:"docdate",     title:"Fecha",       sortable:true },
                    {width: anchoCol*1.00, align:"right",  halign:"right",  field:"total",       title:"Total",       sortable:true },
                    {width: anchoCol*1.50, align:"left",   halign:"left",   field:"islrnumber",  title:"Comprobante", styler:page_docs.grid.format.column.datashw},
                    {width: anchoCol*1.00, align:"right",  halign:"right",  field:"islramount",  title:"Retenido"},
                    {width: anchoCol*0.50, align:"center", halign:"center", field:"pdfshwislr",  title:"&nbsp;",      styler:page_docs.grid.format.column.pdfshwislr},
                    {width: anchoCol*1.75, align:"left",   halign:"left",   field:"ivanumber",   title:"Comprobante", styler:page_docs.grid.format.column.datashw},
                    {width: anchoCol*1.00, align:"right",  halign:"right",  field:"ivaamount",   title:"Retenido"},
                    {width: anchoCol*0.50, align:"center", halign:"center", field:"pdfshwiva",   title:"&nbsp;",      styler:page_docs.grid.format.column.pdfshwiva},
                    {width: anchoCol*0.00, align:"left",   halign:"center", field:"islrpdf",     title:"Error",  hidden:true},
                    {width: anchoCol*0.00, align:"left",   halign:"center", field:"ivapdf",      title:"Error",  hidden:true},
                    {width: anchoCol*0.00, align:"left",   halign:"center", field:"islrstatus",  title:"Error",  hidden:true},
                    {width: anchoCol*0.00, align:"left",   halign:"center", field:"ivastatus",   title:"Error",  hidden:true},
                    {width: anchoCol*0.00, align:"left",   halign:"left",   field:"status",      title:"ST",     hidden:true},
                    {width: anchoCol*0.00, align:"left",   halign:"left",   field:"documentid",  title:"ID",     hidden:true},
                    {width: anchoCol*0.00, align:"left",   halign:"left",   field:"reported",    title:"REP",    hidden:true},
                    {width: anchoCol*0.00, align:"left",   halign:"left",   field:"reportedat",  title:"REP",    hidden:true},
                    {width: anchoCol*0.00, align:"left",   halign:"left",   field:"aproved",     title:"APP",    hidden:true},
                    {width: anchoCol*0.00, align:"left",   halign:"left",   field:"errdsc",      title:"ERR",    hidden:true},
                    {width: anchoCol*0.00, align:"left",   halign:"left",   field:"custstatus",  title:"CUSST",  hidden:true},
                    {width: anchoCol*0.00, align:"left",   halign:"left",   field:"st",          title:"ST",     hidden:true}
                    ]
                ],
                toolbar: [{
                             iconCls: 'stAproved',
                             text: 'Aprobar',
                             handler: page_docs.grid.buttons.approve
                          },'-', {
                             iconCls: 'errorShow',
                             text: 'Rechazar',
                             handler: page_docs.grid.buttons.reject
                          },'-', {
                            iconCls: 'stReported',
                            text: 'Reportar',
                            handler: page_docs.grid.buttons.report.action
                          },'-', {
                               iconCls: 'icon-filter',
                               text: 'Filtro',
                               handler: page_docs.filter.construction
                          }],
                onSelect: function(index,row){
                    $("#grid_area").datagrid("unselectAll", row);
                },
                onClickCell: function(index, field, value){
                    
                    switch (field){
                        case "errshw":      // Estatus de Factura
                            page_docs.grid.showTip.errshw(index);
                            break;
                        case "custid":      // Información del Cliente
                            page_docs.grid.showTip.custid(index);
                            break;
                        case "docnumber":      // Informacion de la factura
                            page_docs.grid.showTip.factura(index);
                            break;
                        case "islrnumber":      // Informacion de la factura
                            page_docs.grid.showTip.retISLR(index);
                            break;
                        case "ivanumber":      // Informacion de la factura
                            page_docs.grid.showTip.retIVA(index);
                            break;
                        case "pdfshwislr":  // PDF del ISLR
                            page_docs.grid.showTip.islrPdf(index);
                            break;
                        case "pdfshwiva":  // PDF del IVA
                            page_docs.grid.showTip.ivaPdf(index);
                            break;
                    }
                },
                onLoadSuccess: function(e){ ////console.log(e);
                    $("#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:350px;position:absolute;top:3px;right:3px;text-align:right;">' +
                               '<input id="buscar" style="width:300px"></input>' +
                               '    <div id="menuBuscar" style="width:200px">' +
                               '        <div data-options="name:\'all\'">Todo</div>' +
                               '        <div data-options="name:\'rif\'">RIF</div>' +
                               '        <div data-options="name:\'custid\'">Cust Id</div>' +
                               '        <div data-options="name:\'nickname\'">Apodo</div>' +
                               '        <div data-options="name:\'name\'">Razón Social</div>' +
                               '        <div data-options="name:\'docdate\'">Fecha de factura</div>' +
                               '        <div data-options="name:\'docnumber\'">Número de factura</div>' +
                               '        <div data-options="name:\'total\'">Total de factura</div>' +
                               '        <div data-options="name:\'islrnumber\'">Comprobante ISLR</div>' +
                               '        <div data-options="name:\'ivanumber\'">Comprobante IVA</div>' +
                               '    </div>' +
                               '</div>';
                    $("#buscarCont").remove();
                    $(".datagrid-toolbar").append(html);
                    $("#buscar").searchbox({
                        prompt:'Buscar...',
                        searcher: function(value, field){
                            page_docs.grid.search = page_docs.filter.filtro;
                            page_docs.grid.search.field = field;
                            page_docs.grid.search.value = value;
                            $('#grid_area').datagrid('load', page_docs.grid.search);
                        },
                        menu: "#menuBuscar"
                    });
                    $("#buscar").searchbox("selectName",page_docs.grid.search.field);
                    $("#buscar").searchbox("setValue",page_docs.grid.search.value);
                    
                    // incluir al scroll del grid para que borre el tip en caso de que se mueva (NO FUNCIONO :()
                    //$(".datagrid-body")[0].addEventListener("scroll", function(){////console.log("xx");$(".infoTip").remove();});
                    
                },
                onLoadError: function(e){
                    ////console.log(e);
                    $.messager.alert("No se puede mostrar la información", e.responseJSON.msg); 
                },
            });
            //page_docs.form.construction();
        }
    }
};
page_docs.on_load();