<style type="text/css">
.ui-jqgrid .ui-jqgrid-pager .ui-pg-div span.ui-icon {
    background-color: #ffffff;
    float: left;
    margin: 0 2px;
}
</style>

<table id="jqGrid"></table>
<div id="jqGridPager"></div>

<script>
findControl = function ()
{
    strFormSerialize = $( 'form' ).serialize();
    relaodGrid( strFormSerialize );
}

relaodGrid = function( s_url_param )
{
    jQuery( '#jqGrid' ).jqGrid( 'clearGridData' );
    jQuery( '#jqGrid' ).jqGrid( 'setGridParam', { url: '<?=buildUrl( 'pro/itemGrid', 'IdAlmacen='.$IdAlmacen )?>?' + s_url_param } );
    jQuery( '#jqGrid' ).trigger( 'reloadGrid' );
}
</script>
<script>
    //reference principal -> http://www.trirand.com/blog/?page_id=5

    var jqGridContent = $( "#jqGrid" );
    var lastsel;
    var object = { TipoCambio : "XXX", getTipoCambio: function(){ return object.TipoCambio; } };
    jqGridContent.jqGrid
    (
        {
            TipoCambio  : "XXX",
            url         : '<?=buildUrl( 'pro/nothing' )?>',
            mtype       : "POST",
            datatype    : "json",
            colNames    : [ 'IdItem', 'UnidadMedida', 'StocCjaRef', 'StocUniRef', 'Codigo', 'Descripcion', 'Marca', 'UniMed', 'Stock', /*'SkFr', 'Precio', 'PrFr',*/ '', '', '', '', '' ],
            colModel    : 
                          [
                            { name: 'IdItem',           width: 0, align: 'center', hidden: true, hidedlg: false, editrules : { required: true }, key: true },
                            { name: 'IdUniMedVenta',    width: 0, align: 'center', hidden: true, hidedlg: false, editrules : { required: true }, key: false },

                            { name: 'CantidadxCaja',    index: "CantidadxCaja", width: 0, align: 'center', hidden: true, hidedlg: false, editrules : { required: true }, key: false },
                            { name: 'CantidadxUnidad',  index: "CantidadxUnidad",  width: 0, align: 'center', hidden: true, hidedlg: false, editrules : { required: true }, key: false },

                            {
                                name: 'IdItem',
                                width: 90, 
                                align: 'center', 
                                editable: false, 
                                sortable: true,
                                formatter: function( cellvalue, options, rowObject )
                                {
                                	return  "<span style='color:blue;text-decoration: underline;cursor:pointer;' originalValue='" + cellvalue + "'>" + cellvalue + "</span>";
                                } 
                            },
                            {
                                name: 'DescripcionCompleta',
                                width: 300,
                                align: 'left',
                                editable: false,
                                sortable: true,
                                formatter: function( cellvalue, options, rowObject )
                                {
                                    return  "<span style='color:blue;text-decoration: underline;cursor:pointer;' >" + cellvalue + "</span>";
                                }
                            },
                            { name: 'Marca',                width: 120, align: 'center', editable: false, sortable: false },
                            { name: 'UniMedVentaDesc',      width: 90, align: 'center', editable: false, sortable: false },
                            {
                                name: 'Stock',      width: 90, align: 'center', editable: true, sortable: false,
                                editoptions:
                                { 
                                    dataInit: function( element ) 
                                    {
                                        //jq(element).attr("readonly", "readonly"); 
                                        pr( arguments );
                                        object.TipoCambio = "XXX";
                                        $( element ).select();
                                    },
                                    dataEvents:
                                    [
                                        {
                                            type: 'click',
                                            fn: function( obj ) 
                                            {
                                                $( obj.currentTarget ).select();
                                            }
                                        },
                                        {
                                            type: 'keypress',
                                            fn: function( obj ) 
                                            {
                                                pr( arguments );
                                                object.TipoCambio = "caja";
                                                pr( object.TipoCambio );
                                            }
                                        },
                                        {
                                            type: 'keyup',
                                            fn: function( obj ) 
                                            {
                                                object.TipoCambio = "caja";
                                            }
                                        }
                                    ]
                                }
                            },
                            {
                                name: 'agree',                width: 30, align: 'center', sortable: false, search: false, 
                                formatter:function( cero, uno, dos, tres )
                                {
                                    //pr( dos );
                                    //var o_Data = arguments[2];
                                    //return "<span style='cursor:pointer; margin: 0 auto;' class='ui-icon ui-icon-circle-triangle-e' title='Agregar Item' onclick=parent.asignarValores( '"+dos.IdItem+"', dos.DescripcionCompleta, dos.IdLote );></span>"
                                    return '<span style="cursor:pointer; margin: 0 auto;" class="ui-icon ui-icon-circle-triangle-e" title="Agregar Item" onclick="parent.asignarValores( \''+dos.IdItem+'\', \''+dos.DescripcionCompleta+'\', \''+dos.IdUniMedVenta+'\' );"></span>'; //\''+dos.IdLote+'\',
                                }
                            },

                            { name: 'Divisor', index: "Divisor",  width: 0, align: 'center', hidden: true, hidedlg: false, editrules : { required: true }, key: false },

                            { name: 'UnidadEquivalenteFlag', index: "UnidadEquivalenteFlag", width: 0, align: 'center', hidden: true, hidedlg: false, editrules : { required: true }, key: false },
                            { name: 'UsoFraccionFlag',       index: "UsoFraccionFlag",       width: 0, align: 'center', hidden: true, hidedlg: false, editrules : { required: true }, key: false },
                            { name: 'EsUnidadMinimaFlag',    index: "EsUnidadMinimaFlag",    width: 0, align: 'center', hidden: true, hidedlg: false, editrules : { required: true }, key: false }
                          ],
			viewrecords : true,
			width       : $(window).width() - 6,
			height      : $(window).height()-150, 
            sortable    : true,
            multiSort   : true,
            emptyrecords: "No se encontro registros",
            rowNum      : 100,
            rownumbers  : true, // show row numbers
            pager       : "#jqGridPager",
            shrinkToFit : false,
            ondblClickRow: function( rowId, param2, param3, param4 ) 
            {
                var s_UniMed      = param4.target.parentNode.children[2].innerHTML;
                var s_Descripcion = param4.target.parentNode.children[7].innerHTML;
                //pr( "ondblClickRow -> " + s_UniMed + " - " + s_Descripcion );

                parent.asignarValores( rowId, s_Descripcion, s_UniMed );
            },
            onCellSelect: function( rowid, iCol, cellcontent )
            {
                if( iCol == 5 ) //Codigo del Item
                {
                    buscarResumenStock( rowid );
                }
                if( iCol == 6 )
                {
                    $( '#myIframe' ).attr( 'src', '<?=buildUrlComplet( 'mst.php/item/mostrarImagen' )?>' + "id_item/" + rowid );
                    $( '#dialog' ).dialog( 'open' );
                }
            },
            //reference -> http://www.guriddo.net/documentation/guriddo/javascript/user-guide/editing/
            //reference -> http://www.trirand.net/documentation/php/_2va196tc2.htm
            //reference ->  http://www.trirand.com/jqgridwiki/doku.php?id=wiki:inline_editing
            //demo -> http://www.guriddo.net/demo/guriddojs/edit_add_delete/inline_on_click/index.html
            onSelectRow: function( id, param2, o_object )
            {
                /*
                if( id && id !== lastsel )
                {
                    jQuery( '#jqGrid' ).jqGrid( 'restoreRow', lastsel );

                    var s_UniMed  = $( o_object.target ).closest( 'tr' ).find( 'td' ).eq( 2 ).html();
                    var s_StkCja  = $( o_object.target ).closest( 'tr' ).find( 'td' ).eq( 3 ).html();
                    var s_StkUni  = $( o_object.target ).closest( 'tr' ).find( 'td' ).eq( 4 ).html();

                    var i_Divisor             = $( o_object.target ).closest( 'tr' ).find( 'td' ).eq( 14 ).html();
                    var UnidadEquivalenteFlag = $( o_object.target ).closest( 'tr' ).find( 'td' ).eq( 15 ).html() == "1" ? true : false;
                    var UsoFraccionFlag       = $( o_object.target ).closest( 'tr' ).find( 'td' ).eq( 16 ).html() == "1" ? true : false;
                    var EsUnidadMinimaFlag    = $( o_object.target ).closest( 'tr' ).find( 'td' ).eq( 17 ).html() == "1" ? true : false;

                    //pr( $( o_object.target ).closest( 'tr' ).find( 'td' ) );
                    pr( id + " - " + s_UniMed + " - " + s_StkCja + " - " + s_StkUni + " - " + i_Divisor + " - " + UnidadEquivalenteFlag + " - " + UsoFraccionFlag + " - " + EsUnidadMinimaFlag );

                    //jQuery( '#jqGrid' ).jqGrid( 'editRow', id, true );
                    //jQuery( "#jqGrid" ).editRow( rowid, keys, oneditfunc, successfunc, url, extraparam, aftersavefunc,errorfunc, afterrestorefunc );
                    jQuery( "#jqGrid" ).editRow
                    ( 
                        id, 
                        true, 
                        null, //oneditfunc, 
                        function( o_result )
                        {
                            var o_json = jQuery.parseJSON( o_result.responseText );
                            //pr( o_json );

                            if( o_json.error )
                            {
                                parent.mostrarMensajeError( o_json.mensaje_error );
                            }
                            parent.executeFindDetail();
                            parent.b_GuardarItem = false;
                            //parent.closePopup();
                            parent.ocultarModal( "exampleModalCenter" );
                            return false;
                        }, //successfunc, 
                        null, //url, 
                        //{ "IdMedida":s_UniMed, "i_Id":s_Id, "StkCjaRef":s_StkCja, "StkUniRef":s_StkUni, "TipoCambio":object.getTipoCambio() }, //extraparam, 
                        {
                            "IdMedida":s_UniMed, "StkCjaRef":s_StkCja, "StkUniRef":s_StkUni,
                            TipoCambio: function()
                            {
                                //pr( object.getTipoCambio() );
                                return object.getTipoCambio();
                            }
                        },
                        null, //aftersavefunc,
                        null, //errorfunc, 
                        null //afterrestorefunc 
                    );
                    lastsel = id;

                    if( ( !UnidadEquivalenteFlag && !UsoFraccionFlag && EsUnidadMinimaFlag ) || ( UnidadEquivalenteFlag && !UsoFraccionFlag && !EsUnidadMinimaFlag ) )
                    {
                        $( "#" + id + "_CantidadxCaja" ).prop( "disabled", false );
                        $( "#" + id + "_CantidadxUnidad" ).prop( "disabled", true );

                        if( parseFloat( s_StkCja ) <= 0 )
                        {
                            $( "#" + id + "_CantidadxCaja" ).prop( "disabled", true );
                        }
                        else
                        {
                            $( "#" + id + "_CantidadxCaja" ).focus();
                        }
                    }
                    if( UnidadEquivalenteFlag && UsoFraccionFlag && !EsUnidadMinimaFlag ) //podria ser, los que aceptan fracciones
                    {
                        //$( "#" + id + "_CantidadxCaja" ).prop( "disabled", false );
                        //$( "#" + id + "_CantidadxUnidad" ).prop( "disabled", false );

                        if( parseFloat( s_StkCja ) <= 0 && parseFloat( s_StkUni ) > 0 )
                        {
                            $( "#" + id + "_CantidadxCaja" ).prop( "disabled", true );
                            $( "#" + id + "_CantidadxUnidad" ).prop( "disabled", false );
                            $( "#" + id + "_CantidadxUnidad" ).focus();
                        }
                        if( parseFloat( s_StkCja ) <= 0 && parseFloat( s_StkUni ) <= 0 )
                        {
                            $( "#" + id + "_CantidadxCaja" ).prop( "disabled", true );
                            $( "#" + id + "_CantidadxUnidad" ).prop( "disabled", true );
                        }
                    }
                    
                }
                */
            },
            editurl: "<?=buildUrlComplet( $module."/".$controler, "s_TipoProc=nvodet&moneda_cod=$moneda_cod&IdAlmacen=$IdAlmacen&i_Id=$i_Id&id_adicional=$id_adicional" )?>"
        }
    );

    //$( "#jqGrid" ).jqGrid( 'bindKeys' ); // esto habilita bajar las celdas con las tecla de arriba y abajo
    
    //un ejemplo para ver mas opciones al metodo bindKeys
    /* jQuery("#keynav").jqGrid('bindKeys', { "onEnter" : function( rowid ) { alert("You enter a row with id:"+rowid) } }); */

    // habilita la opcion de editar los campos con el flag editar true
    jQuery( "#jqGrid" ).jqGrid( 'navGrid', "#jqGridPager", { edit:false, add:false, del:false, view: false, search: false, refresh: false } )
    .jqGrid( 'navButtonAdd', "#jqGridPager", 
        {
            caption:"STOCK-MIN",
            buttonicon:"ui-icon-circle-plus",
            onClickButton:function()
            { 
                /*
                var dataFromTheRow = jQuery('#list').jqGrid ('getRowData', rowId);
                var dataFromCellByColumnIndex = jQuery('#list').jqGrid ('getCell', rowId, 7);
                var dataFromCellByColumnName = jQuery('#list').jqGrid ('getCell', rowId, 'Tax');
                */

                var myGrid = $( '#jqGrid' );
                var rowId  = myGrid.jqGrid( 'getGridParam', 'selrow' );
                //var objData = myGrid.jqGrid ('getRowData', rowId ); 
                //var stock = myGrid.jqGrid ( 'getCell', rowId, 9 ); // cantidad por unidad
                var stock = 0; // cantidad por unidad // por defecto 0
                var desc  = myGrid.jqGrid ( 'getCell', rowId, 7 ); // descripcion de la unidad de medida
                /*
                x = confirm( "Esta seguro de activar el Stock Minimo del Item [" + desc + "] ? " );
                if( x )
                {
                    $.ajax
                    (
                        {
                            url: "<?=buildUrlComplet( 'mst.php/item/addStockMin', 'id_item=' )?>" + rowId + "/stock/" + stock + "/value/Y",
                            async: false, 
                            //very important: else php_data will be returned even before we get Json from the url
                            dataType: 'json',
                            success: function ( json ) 
                            {
                                pr( json );
                                if( json.error )
                                {
                                    alert( json.mensaje_error );
                                    return false;
                                }
                                //$( '#myIframe2' ).attr( 'src', '<?=buildUrlComplet( 'mst.php/item/listStkMin', '' )?>' );
                                //$( '#dialog2' ).dialog( 'open' );
                            }
                        }
                    );
                }*/
            },
            position: "last",
            title:"",
            id : "",
            cursor: "pointer"
        }
    );
    //jQuery( "#jqGrid" ).jqGrid( 'inlineNav',"#jqGridPager" );

    //reference -> http://www.trirand.com/jqgridwiki/doku.php?id=wiki:events
    //reference -> http://www.trirand.com/jqgridwiki/doku.php?id=wiki:methods
    /*
    $( "#jqGrid" ).bind
    (
        "jqGridKeyEnter",
        function ( obj, rowId )
        {
            var rowData = jQuery('#jqGrid').jqGrid ( 'getRowData', rowId );
            var s_Descripcion = rowData.DescripcionCompleta;
            var s_UniMed = rowData.IdUniMedVenta;

            parent.asignarValores( rowId, s_Descripcion, s_UniMed );

            return false;
        }
    );
    */

    $(window).on
    ( 
        "resize", 
        function () 
        {
            var newWidth = $( "#jqGrid" ).closest( ".ui-jqgrid" ).parent().width() - 5;
            if( newWidth <= 705 )
            {
                jqGridContent.jqGrid( "setGridWidth", newWidth, false );
            }
            else
            {
                jqGridContent.jqGrid( "setGridWidth", newWidth, true);
            }
        }
    );
    if( $( "#jqGrid" ).closest( ".ui-jqgrid" ).parent().width() <= 705 )
    {
        jqGridContent.jqGrid( "setGridWidth", $( "#jqGrid" ).closest( ".ui-jqgrid" ).parent().width() - 5, false );
    }
    else
    {
        jqGridContent.jqGrid( "setGridWidth", $( "#jqGrid" ).closest( ".ui-jqgrid" ).parent().width() - 5, true);
    }
    if( $( "#jqGrid" ).closest( ".ui-jqgrid" ).parent().width() <= 558 )
    {
        jqGridContent.jqGrid( "setGridHeight", $( "#jqGrid" ).closest( ".ui-jqgrid" ).parent().height() - 100, false );
    }

    setTimeout
    (
        function()
        {
            findControl();
            $( "#jqGrid" ).parents( 'div.ui-jqgrid-bdiv' ).css( "height", ($(window).height()-150) );
        },
        300
    );
</script>
<?=crearPopupResumenStock( array( "name_function"=>"buscarResumenStock", "modal"=>"true" ) )?>
<?=crearFuentePopupIframe( array( "div_id"=>"dialog", "iframe_id"=>"myIframe", "popup_title"=>"Imagen", "popup_width"=>"300", "popup_height"=>"300", "modal"=>true ) )?>