		$(function(){
			$('#dg').datagrid({
				view: detailview,
				detailFormatter:function(index,row){
					return '<div class="ddv"></div>';
				},
				onExpandRow: function(index,row){
					var ddv = $(this).datagrid('getRowDetail',index).find('div.ddv');
					//alert(index);
					ddv.panel({
						border:false,
						cache:true,
						href:'show_form.php?index='+index,
						onLoad:function(){
							$('#dg').datagrid('fixDetailRowHeight',index);
							$('#dg').datagrid('selectRow',index);
							$('#dg').datagrid('getRowDetail',index).find('form').form('load',row);
						}
					});
					$('#dg').datagrid('fixDetailRowHeight',index);
				},
                onSelect: function(rowIndex, rowData){
                    var row = $('#dg').datagrid('getSelected'); 
                    cargar(row.id);
                }
			});
            var panel = $('#dg').datagrid('getPanel').attr('tabindex', 0).focus();
            panel.bind('keydown', function(e) {
            switch (e.keyCode) {
            case 38: // up
            selectRow(true);
            return false;
            case 40: // down
            selectRow(false);
            return false;
            }
            });            
		});
		function saveItem(index){
			var row = $('#dg').datagrid('getRows')[index];
			var url = row.isNewRecord ? 'index_rdb/save.php' : 'index_rdb/update.php?id='+row.id;
			$('#dg').datagrid('getRowDetail',index).find('form').form('submit',{
				url: url,
				onSubmit: function()
				{
					if  (!($('#pr').combobox('getValue'))||
	    				     !($('#ma').combobox('getValue'))||
	    				     !($('#su').combobox('getValue'))||
	    				     !($('#gr').combobox('getValue'))
					    ) 
					{ 
						$.messager.alert('Error','Complete los combos antes de grabar','warning');
						return False;
						exit;
					} 
					var text = document.getElementById("va").value	;
					if(isNaN(text))
						{
							$.messager.alert('Error','El valor del Limite debe ser numérico','warning');
							return False;
							exit;
						} 
					var text = document.getElementById("or").value	;
					if(isNaN(text))
						{
							$.messager.alert('Error','El valor del Orden debe ser numérico','warning');
							return False;
							exit;
						} 
					show();
				},
				success: function(result){
					doSearch();	
				},
			
			});
		}
		function cancelItem(index){
			var row = $('#dg').datagrid('getRows')[index];
			if (row.isNewRecord){
				$('#dg').datagrid('deleteRow',index);
			} else {
				$('#dg').datagrid('collapseRow',index);
			}
		}
		function destroyItem(){
			var row = $('#dg').datagrid('getSelected');
			if (row){
				$.messager.confirm('Confirme por favor..','¿Seguro de Borrar este registro?',function(r){
					if (r){
						var index = $('#dg').datagrid('getRowIndex',row);
						$.post('index_rdb/destroy.php',{id:row.id},function(){
							$('#dg').datagrid('deleteRow',index);
						});
					}
				});
			}
		}
		function newItem(){
			$('#dg').datagrid('appendRow',{isNewRecord:true});
			var index = $('#dg').datagrid('getRows').length - 1;
			$('#dg').datagrid('expandRow', index);
			$('#dg').datagrid('selectRow', index);
		}


        function doSearch(){
            $('#dg').datagrid('load',{
            producto: $('#prf').combobox('getValue'),
            matriz: $('#maf').combobox('getValue'),
            sustancia: $('#suf').combobox('getValue'),
            grupo: $('#grf').combobox('getValue')
    });
   }        
   
   
       
   
   		function show(){
			$.messager.show({
				title:'Grabado',
				msg:'Grabado en Base de Datos.',
				showType:'show'
			});
		}
    $('#prf').combobox({selectOnNavigation:$(this).is(':checked')})
    $('#maf').combobox({selectOnNavigation:$(this).is(':checked')})
    $('#suf').combobox({selectOnNavigation:$(this).is(':checked')})
    $('#grf').combobox({selectOnNavigation:$(this).is(':checked')})
    
    function cargar(id){
            $.ajax({   
                type: "GET",
                datatype:"JSON",
                url:"index_rdb/get_detalle.php?id="+id,
                success: function(data){     
  
                    data = JSON.parse(data); 
                    document.getElementById("limite_id").value=data.id;
                    $('#cmbProducto').combobox('select', data.producto_id);
                    $('#cmbMatriz').combobox('select', data.matriz_id);
                    $('#cmbSustancia').combobox('select', data.sustancia_id);
                    $('#cmbGrupo').combobox('select', data.grupo_id);
                    document.getElementById("comentario").value=data.comentario;
                    document.getElementById("orden").value=data.orden;
                    document.getElementById("valor").value=data.valor;
                }
            });            
            
    }
    
function selectRow(up){
    var t = $('#dg');
    var count = t.datagrid('getRows').length;    // row count
    var selected = t.datagrid('getSelected');
    if (selected){
        var index = t.datagrid('getRowIndex', selected);
        index = index + (up ? -1 : 1);
        if (index < 0) index = 0;
        if (index >= count) index = count - 1;
        t.datagrid('clearSelections');
        t.datagrid('selectRow', index);
    } else {
        t.datagrid('selectRow', (up ? count-1 : 0));
    }
}

     function print_it(){ 
         if  (!($('#dg').datagrid('getSelected'))) 
         {
            $.messager.show({
                title:'Impresion',
                msg:'Selecione registro.',
                timeout:5000,
                showType:'slide'
            }); 
         } else 
         {
            $.messager.show({
                title:'Impresion',
                msg:'Procesado.',
                timeout:5000,
                showType:'slide'
            }); 
            
         }
        var row = $('#dg').datagrid('getSelected'); 
        var oDados
        oDados = document.getElementById('id');  
        oDados.value = row.id;
        
        $('#form-printer').submit(); 
        };  

        function submitForm(){
            $('#ff1').form('submit');
            setTimeout(function(){$('#dg').datagrid('reload')},500);
        }
        function clearForm(){
            $('#ff1').form('clear');
            $('#dg').datagrid('reload');
        }
        function Alta(){
            document.getElementById('limite_id').value="ALTA";
        }
        
     $('#cmbProducto').combobox({
                url:'index_rdb/get_combo_data.php?tabla=productos',
                valueField:'id',
                        textField:'nombre'
                });

     $('#cmbMatriz').combobox({
                url:'index_rdb/get_combo_data.php?tabla=matrices',
                valueField:'id',
                        textField:'nombre'
                });

     $('#cmbGrupo').combobox({
                url:'index_rdb/get_combo_data.php?tabla=grupos',
                valueField:'id',
                        textField:'nombre'
                });

     $('#cmbSustancia').combobox({
                url:'index_rdb/get_combo_data.php?tabla=sustancias',
                valueField:'id',
                        textField:'nombre'
                });

                
