Ext.ns("app.informes.layout");
var acceso = function() {
    
   var loginForm = new Ext.form.FormPanel({
    		border:true,
    		frame:false,
            id:'loginForm',
    		width:200,       
            bodyStyle   :'padding:5px', 
    		items: [
                new Ext.form.TextField({
        			id:"usuario",
                    width   :100,
        			fieldLabel:"Usuario",
        			allowBlank:false,
        			blankText:"Ingresa usuario"
        		}),
        		new Ext.form.TextField({
        			id:"password",
                    width   :100,
        			fieldLabel:"Password",
        			inputType: 'password',
        			allowBlank:false,
        			blankText:"Ingresa password",
        			enbledKeyEvents:true,
        			listeners:{
        				scope	:this,
        				specialkey	:function(el,e){
        					if(e.keyCode == e.ENTER) 
        						if(Ext.getCmp('usuario').isValid() && Ext.getCmp('password').isValid())
        							Ext.getCmp('loginForm').getForm().submit({
            							url: 'ctrlogin',
                                        scope : this,                  
            							waitMsg: 'Validando datos',
            							failure: function(){
									msgERROR('Validación fallida','Verifique sus datos y vuelva a intentarlo');
															
								},
            							success: function(form,action){
            								var json=Ext.util.JSON.decode(action.response.responseText);
                                            loginWindow.destroy();
                                            Ext.getCmp('cargainicial').getStore().load({
                                                    params:{ban:1}
                                            });
                                            Ext.getCmp('panelusuario').body.update(json.nombre);
                                            if(json.id==null)
                                                Ext.getCmp('administrador').disable();
        							
            							}
        							});  
                                else
                                    msgALERTA('Aviso','Ingrese campos obligatorios');         				
                        }
        			}
        		})
            ]
    	});
    
    	var loginWindow = new Ext.Window({
    		layout: 'fit',                 
            height  :150,
    		width: 300,
            iconCls:'acceso',
            title   :'Acceso Mesa de Ayuda',
    		border:false,                            
    		modal	:true,                            
    		closable: false,
    		resizable: false,                              
    		draggable: false,
            items: [
                loginForm,
                new Ext.form.FormPanel({
                    border:true,
                    frame:false,
                    width:200,       
                    bodyStyle   :'padding:5px', 
                    items: [
                    ]
                })
            ],
            bbar    :[
                '-',
                {text:'Darme de alta',iconCls:'addusuario',handler:function(){
                    this.Wnuevo=new Ext.Window({
                        title   :'Alta de usuario',
                        width   :500,
                        height  :150,
                        layout  :'fit',
                        id  :'Wnuevo',
                        modal   :true,
                        items   :[
                            new Ext.form.FormPanel({
                                frame   :false,
                                border  :false,
                                id  :'formnuevousuario',
                                bodyStyle:'padding:5px',
                                items   :[
                                    {
                                        xtype:'fieldset',
                                        title: 'Ingrese No.empleado, correo electronico y posteriormente de ENTER',
                                        autoHeight:true,
                                        items :[{
                                                xtype:'numberfield',
                                                fieldLabel: 'No. Empleado',
                                                width:50,
                                                name: 'noempalta',
                                                allowBlank:false,
                                                allowDecimals:false,
                                                allowNegative:false
                                            },{
                                                xtype:'textfield',
                                                fieldLabel: 'Email',
                                                width:250,
                                                blankText:'Este campo solo admite una direccion de correo elecrtronico',
                                                name: 'email',
                                                vtype:'email',
                                                enbledKeyEvents:true,
                                    			listeners:{
                                    				scope	:this,
                                    				specialkey	:function(el,e){
                                    					if(e.keyCode == e.ENTER) 
                                    						if(Ext.getCmp('formnuevousuario').getForm().isValid())
                                    							Ext.getCmp('formnuevousuario').getForm().submit({
                                        							url: 'ctrlogin/nuevousuario',
                                                                    scope : this,                  
                                        							waitMsg: 'Validando datos',
                                        							failure: function(form,action){
													var json=Ext.util.JSON.decode(action.response.responseText);
													if(json.error==1)
														msgERROR('Validación fallida','Verifique sus datos y vuelva a intentarlo');
													else if (json.error==2)
														msgALERTA('Aviso','Su usuario ya existe, recupere su password por medio de la opcion Olvide mi password');
													else
														msgALERTA('Aviso','Imposible registrar usuario, si Usted labora en una Libreria registre su reporte por medio del Weblib(http://weblib.educal.com.mx), gracias');

												},
                                        							success: function(form,action){
                                        								var json=Ext.util.JSON.decode(action.response.responseText);
                                                                        msgINFO('Informacion','Se ha registrado correctamente, los datos de acceso le han sido enviados a su correo')
                                                                        Ext.getCmp('Wnuevo').destroy();
                                    							     }
                                    							});  
                                                            else
                                                                msgALERTA('Aviso','Ingrese datos obligatorios por favor ...');         				
                                                    }
                                    			}
                                            }
                                        ]
                                    }
                                ]
                            })
                        ] 
                    });
                    this.Wnuevo.show();       
                }},'-',
                {xtype:'tbfill'},
                '-',
                {text:'Olvide mi password',iconCls:'password',handler:function(){
                    this.Wolvido=new Ext.Window({
                        title   :'Restablecer Password',
                        width   :300,
                        height  :150,
                        layout  :'fit',
                        id  :'Wolvido',
                        modal   :true,
                        items   :[
                            new Ext.form.FormPanel({
                                frame   :false,
                                border  :false,
                                id  :'formreestablece',
                                bodyStyle:'padding:5px',
                                items   :[
                                    {
                                        xtype:'fieldset',
                                        autoHeight:true,
                                        title   :'Ingrese No.Empleado y de ENTER',
                                        autoHeight:true,
                                        items :[{
                                                xtype:'numberfield',
                                                fieldLabel: 'No. Empleado',
                                                width:50,
                                                name: 'noempreestablece',
                                                allowBlank:false,
                                                allowDecimals:false,
                                                allowNegative:false,
                                                enbledKeyEvents:true,
                                    			listeners:{
                                    				scope	:this,
                                    				specialkey	:function(el,e){
                                    					if(e.keyCode == e.ENTER) 
                                    						if(Ext.getCmp('formreestablece').getForm().isValid())
                                    							Ext.getCmp('formreestablece').getForm().submit({
                                        							url: 'ctrlogin/reestablece',
                                                                    scope : this,                  
                                        							waitMsg: 'Validando datos',
                                        							failure: function(){msgERROR('Validación fallida','Verifique sus datos y vuelva a intentarlo');},
                                        							success: function(form,action){
                                        								var json=Ext.util.JSON.decode(action.response.responseText);
                                                                        msgINFO('Informacion','Su clave le ha sido enviada por correo electronico')
                                                                        Ext.getCmp('Wolvido').destroy();
                                    							     }
                                    							});  
                                                            else
                                                                msgALERTA('Aviso','Ingrese numero de empleado por favor ...');         				
                                                    }
                                    			}
                                            }
                                        ]
                                    }
                                ]
                            })
                        ] 
                    });
                    this.Wolvido.show();
                }},'-'
            ],
    		listeners	:{
	            show    :function(){
	                Ext.getCmp('usuario').focus(true,500);  
	            }
            }
        });
        loginWindow.show();  
    
};

var Fcomentario=function(id_reporte,Elgrid){
    var Wincomentario = new Ext.Window({
            title  :'Agregar comentarios. Reporte No.'+id_reporte,
            height  : 300,
            modal : true,
            width : 500,
            layout : 'fit',
            id :'Wincomentario',
            resizable : true,                                                         
            tbar :[
                {xtype:'tbfill'},
                {text:'Registrar comentario', iconCls:'guardar', handler:function(){
                    if (Ext.getCmp('formcomentario').getForm().isValid())
                        Ext.getCmp('formcomentario').getForm().submit({
                            url : 'ctrregistro/agregarcomentario',
                            params : {id:id_reporte},
                            waitMsg : 'Registrando comentario',
                            success : function(){  
                                Elgrid.getStore().load({
                                    params: {id:id_reporte}
                                });  
                                msgINFO('Informacion','Comentario ingresado con exito');     
                                Ext.getCmp('Wincomentario').destroy();                                              
                            }
                        });
                    else
                        msgALERTA('Aviso','Ingrese comentario ....');                                        
                }},
            ],                          
            items :[  
                new Ext.form.FormPanel({
                    id : 'formcomentario',
                    frame : false,
                    border : false,
                    bodyStyle:'padding:5px',
                    items :[                                             
                        new Ext.form.TextArea({
                            name: 'comentario',
                            id  : 'comentario',
                            width : 300,
                            height: 150,
                            allowBlank : false,
                            blankText : 'Ingrese comentarios ',
                            fieldLabel : 'Registre su comentario '                                  
                        })                            
                    ]                                                                                                                   
                })
            ]
        });
    Wincomentario.show();    
};

var VerAdjunto=function(nombre,nombre_original){
    var Visor=new Ext.Window({
		title	:nombre_original,
		maximizable	:true,
		minimizable	:true,
		closable	:true,
		width	:800,
		height	:500,
		titleCollapse	:true,
		html	:'<iframe src="./adjuntos/'+nombre+'" border="none" width="100%" height="100%">'		
	});
	Visor.show();
};

var msgERROR = function(title, msg){
            Ext.Msg.show({
            title: title,
            msg: msg,
            minWidth: 300,
            modal: true,
            icon: Ext.Msg.ERROR,
            buttons: Ext.Msg.OK
        	});
};
var msgALERTA = function(title, msg){
        	Ext.Msg.show({
            title: title,
            msg: msg,
            minWidth: 300,
            modal: true,
            icon: Ext.Msg.WARNING,
            buttons: Ext.Msg.OK
        	});
};

var msgINFO = function(title, msg){
        	Ext.Msg.show({
            title: title,
            msg: msg,
            minWidth: 300,
            modal: true,
            icon: Ext.Msg.INFO,
            buttons: Ext.Msg.OK
        	});
};
app.informes.layout={
    init:function(){
        Ext.QuickTips.init();
        Ext.form.Field.prototype.msgTarget = 'side';

        var cargainicial=new Ext.grid.GridPanel({
            title:'Reportes solucionados, pendientes de FINALIZAR..........',
            region  :'center',
            stripeRows  :true,
            columnLines :true,
            border  :true,
	     margins:'2 2 2 2',
            id  :'cargainicial',
            tools   :[
                {id:'refresh',qtip:'Actualizar',handler:function(){
                    Ext.getCmp('cargainicial').getStore().reload();
                }}
            ],
            store   :new Ext.data.JsonStore({
                proxy   :new Ext.data.HttpProxy({
                    api :{read:'ctrregistro/consultas_resultado'},
                    method  :'POST'
                    
                }),
                root    :'data',
                fields:[
                    {name:'id',type:'integer'},
                    {name:'fecha_registro'},
                    {name:'actividad'},
                    {name:'observaciones'},
                    {name:'status'},
                    {name:'fecha_asignacion'},
                    {name:'fecha_atencion'},
                    {name:'fecha_solucion'},
                    {name:'fecha_finalizacion'},
                    {name:'fecha_cancelacion'}
                ]   
            }),
            columns :[
                new Ext.grid.RowNumberer(),
                {header:'No.Reporte',dataIndex:'id',width:75,sortable:true},
                {header:'Status',dataIndex:'status',width:75,sortable:true},
		  {header:'Actividad',dataIndex:'actividad',width:300,sortable:true},
                {header:'Fecha Registro',dataIndex:'fecha_registro',width:100},
                {header:'Fecha Asignacion',dataIndex:'fecha_asignacion',width:100},
                {header:'Fecha Atencion',dataIndex:'fecha_atencion',width:100},
                {header:'Fecha Solucion',dataIndex:'fecha_solucion',width:100},
                {header:'Fecha Finalizacion',dataIndex:'fecha_finalizacion',width:100},
                {header:'Fecha Cancelacion',dataIndex:'fecha_cancelacion',width:100}
             ] 
            
        });

	var panelobservacionesusuario= new Ext.Panel({
       	region: 'east',
       	border:true,
       	margins:'2 2 2 2',
       	title:'Descripcion del problema',
       	collapsible:true,
       	split:true,
       	id:'panelobservacionesusuario',
       	bodyStyle:'padding:5px; font-size:14px',      
       	width: '30%'
    	});

        var panelusuario=new Ext.Panel ({
            region :'south',
            height : 50,
            title  :'Usuario: ',
            margins :'2 2 2 2',
            bodyStyle:'font-family:arial;font-size:14px;padding:5px',
            id : 'panelusuario'            
        });

        var datos=new Ext.Panel({
            region  :'center',
	     layout:'border',
            id  :'descripcion',
            margins :'2 2 2 2',
            height  :300,
            border:false,
            items:[cargainicial,panelobservacionesusuario]
            
        });
        
        var menu=new Ext.Panel({
            id  :'menu',
            title   :'EDUCAL. MAAGTIC - Mesa de Ayuda',
            region  :'north',
            margins :'2 2 2 2',
            border  :false,
            tbar    :{
                defaults:{
                    iconAlign   :'top'
                },
                items   :[
                    {text   :'Registrar',iconCls:'registrar',id:'registrar',scale:'large', handler:function(){ // REGISTRAR REPORTE
                        Ext.Ajax.request({
				url:'ctrregistro/verificareportes',
				method:'POST',
				success:function(response,request){
					var json=Ext.decode(response.responseText);
					if(json.cantidad>=4)
						msgALERTA('Aviso','Finalice sus reportes por favor...');
					else{
						Ext.getCmp('registrar').disable();
                        var formregistra= new Ext.form.FormPanel({
                            id : 'formregistra',
                            region  :'center',
                            margins :'2 2 2 2',
                            frame : false,
                            border : true,
                            bodyStyle:'padding:5px',
                            items :[
                                new Ext.form.ComboBox({
                                  name : 'tipo',
                                  id : 'tipo',
                                  allowBlank : false,
                              //    mode : 'local',
                                  triggerAction:'all',   //trae los datos del query
                                  displayField : 'descripcion',
                                  valueField : 'id',
                                  emptyText : 'Seleccione ...',
                                  hiddenName : 'tipo',
                                  editable : false,
                                  width : 400,
                                  listeners:{
                                    select : function (combo,registro,indice){
                                        Ext.getCmp('familia').enable();
                                        Ext.getCmp('familia').clearValue();
                                        Ext.getCmp('actividad').clearValue();
                                        Ext.getCmp('actividad').disable();
                                        Ext.getCmp('familia').getStore().load({params:{id:combo.getValue()}});    
                                       }                                                                                            
                                  },                                 
                                  fieldLabel :'Servicio ',
                                  store : new Ext.data.JsonStore({
                                    proxy : new Ext.data.HttpProxy({   //se especifica a que archivo php va a consultar
                                        api :{
                                            read : 'ctrregistro/catalogo_tipo'                                           
                                        },
                                        method : 'post'
                                        }),
                                    root : 'data',
                                    fields : [
                                        {name :'id'},
                                        {name :'descripcion'} 
                                    ]
                                  }) //crear nuevo objeto store de datos   
                                    
                                }),
                                  new Ext.form.ComboBox({
                                  name : 'familia',
                                  disabled : true,
                                  id : 'familia',
                                  mode: 'local',
                                  allowBlank : false,
                                  triggerAction:'all',   //trae los datos del query
                                  displayField : 'descripcion',
                                  valueField : 'id',
                                  emptyText : 'Seleccione ...',
                                  hiddenName : 'familia',
                                  editable : false,
                                  width :400,     
                                  listeners:{
                                    select : function (combo,registro,indice){
                                        Ext.getCmp('actividad').enable();
                                        Ext.getCmp('actividad').clearValue();
                                        Ext.getCmp('actividad').getStore().load({params:{id:combo.getValue()}});    
                                       }                                                                                            
                                  },                            
                                  fieldLabel :'Categoria ',
                                  store : new Ext.data.JsonStore({
                                    proxy : new Ext.data.HttpProxy({   //se especifica a que archivo php va a consultar
                                        api :{
                                            read : 'ctrregistro/catalogo_familia'                                           
                                        },
                                        method : 'post'
                                        }),
                                    root : 'data',
                                    fields : [
                                        {name :'id'},
                                        {name :'descripcion'} 
                                    ]
                                  }) //crear nuevo objeto store de datos   
                                    
                                }),
                                   new Ext.form.ComboBox({
                                  name : 'actividad',
                                  disabled : true,
                                  id : 'actividad',
                                  mode: 'local',
                                  allowBlank : false,
                                  triggerAction:'all',   //trae los datos del query
                                  displayField : 'descripcion',
                                  valueField : 'id',
                                  emptyText : 'Seleccione ...',
                                  hiddenName : 'actividad',
                                  editable : false,
                                  width : 400,                                 
                                  fieldLabel :'Actividad',
                                  store : new Ext.data.JsonStore({
                                    proxy : new Ext.data.HttpProxy({   //se especifica a que archivo php va a consultar
                                        api :{
                                            read : 'ctrregistro/catalogo_actividad'                                           
                                        },
                                        method : 'post'
                                        }),
                                    root : 'data',
                                    fields : [
                                        {name :'id'},
                                        {name :'descripcion'} 
                                    ]
                                  }) //crear nuevo objeto store de datos   
                                    
                                }),
                                new Ext.form.TextArea({
                                    name: 'observacion',
                                    id  : 'observacion',
                                    width : 300,
                                    maxLength   :500,
                                    maxLengthText   :'Este campos solo admite 500 caracteres',
                                    height: 150,
                                    fieldLabel : 'Observaciones '                                  
                                })                            
                            
                            ]                                                                                 
                        });
                        
                        var gridactividad=new Ext.grid.GridPanel({
                            title:'Buscador de actividades',
                            region  :'south',
                            height  :300,
                            margins :'2 2 2 2',
                            stripeRows  :true,
                            columnLines :true,
                            border  :true,
                            id  :'gridactividad',
                            tbar    :[
                                {xtype:'label',text:'Actividad a buscar:'},
                                {xtype:'textfield',name:'cadena',id:'cadena',width:250}
                            ],
                            tools   :[
                                {id:'search',qtip:'Buscar',handler:function(){
                                    Ext.getCmp('gridactividad').getStore().load({
                                        params:{cadena:Ext.getCmp('cadena').getValue()}
                                    });       
                                }}
                            ],
                            store   :new Ext.data.JsonStore({
                                proxy   :new Ext.data.HttpProxy({
                                    api :{read:'ctrregistro/buscadoractividad'},
                                    method  :'POST'
                                    
                                }),
                                root    :'data',
                                fields:[
                                    {name:'id'},
                                    {name:'servicio'},
                                    {name:'categoria'},
                                    {name:'actividad'},
                                    {name:'id_tipo'}
                                ]   
                            }),
                            autoExpandColumn:'actividad',
                            columns :[
                                new Ext.grid.RowNumberer(),
                                {header:'ID',dataIndex:'id',width:30},
                                {header:'Servicio',dataIndex:'servicio',width:150},
                                {header:'Categoria',dataIndex:'categoria',width:150},
                                {header:'Actividad',id:'actividad',dataIndex:'actividad',width:150,sortable:true}
                            ] 
                        });
                            
                        var winregistra=new Ext.Window({
                            title  :'Registro de reporte',
                            height  : 625,
                            width : 800,
                            border  :false,
                            layout : 'border',
                            id :'winregistra',
                            resizable : false,
                            collapsible : true,
                            tbar :[
                                {xtype:'tbfill'},
                                '-',
                                {text:'Registrar',iconCls:'guardar',handler:function(){
                                   if (Ext.getCmp('formregistra').getForm().isValid())
                                        Ext.getCmp('formregistra').getForm().submit({
                                            url: 'ctrregistro/registrar',
                                            waitMsg : 'Espere.. registrando reporte ..',
                                            success: function(form,action){
                                                var json=Ext.decode(action.response.responseText);
                                                Ext.getCmp('winregistra').destroy();
                                                Ext.getCmp('registrar').enable();
                                                msgINFO('Información','No. de reporte asignado '+json.id);   
                                            },
                                            failure : function(){
                                                
                                                msgERROR('Error ','Problema al registrar el reporte');                                                
                                            }
                                            
                                        });
                                   else
                                        msgALERTA('Aviso','Debe registar datos obligatorios');
                                    
                                }}
                            ],
                            listeners : {
                                close: function(){
                                    Ext.getCmp('registrar').enable();
                                    
                                }
                                
                            },
                            items : [formregistra,gridactividad]                                                      
                          });
                        winregistra.show();
					
					}// finaliza si es menos de 4 reportes
				}
			   });                
                    }},
                    
                    '-',
                    //**** CONSULTA DE REPORTES *************************
                    
                    {text   :'Consultar',id:'consulta',iconCls:'buscar',scale:'large',handler:function(){
                        Ext.getCmp('consulta').disable();
                        var gridconsultas=new Ext.grid.GridPanel({
                            title:'Resultados de la busqueda',
                            region  :'center',
                            stripeRows  :true,
                            border  :false,
                            id  :'gridconsultas',
                            store   :new Ext.data.JsonStore({
                                proxy   :new Ext.data.HttpProxy({
                                    api :{read:'ctrregistro/consultas_resultado'},
                                    method  :'POST'
                                    
                                }),
                                root    :'data',
                                fields:[
                                    {name:'id'},
                                    {name:'fecha_registro'},
                                    {name:'actividad'},
                                    {name:'observaciones'},
                                    {name:'status'},
                                    {name:'fecha_asignacion'},
                                    {name:'fecha_atencion'},
                                    {name:'fecha_solucion'},
                                    {name:'fecha_finalizacion'},
                                    {name:'fecha_cancelacion'}
                                ]   
                            }),
                            columns :[
                                new Ext.grid.RowNumberer(),
                                {header:'No.Reporte',dataIndex:'id',width:75,sortable:true},
                                {header:'Status',dataIndex:'status',width:75,sortable:true},
                                {header:'Fecha Registro',dataIndex:'fecha_registro',width:100},
                                {header:'Actividad',dataIndex:'actividad',width:300,sortable:true},
                                {header:'Observaciones',dataIndex:'observaciones',width:300},
                                {header:'Fecha Asignacion',dataIndex:'fecha_asignacion',width:100},
                                {header:'Fecha Atencion',dataIndex:'fecha_atencion',width:100},
                                {header:'Fecha Solucion',dataIndex:'fecha_solucion',width:100},
                                {header:'Fecha Finalizacion',dataIndex:'fecha_finalizacion',width:100},
                                {header:'Fecha Cancelacion',dataIndex:'fecha_cancelacion',width:100}
                            ]   
                        });
        
                        this.gridadjuntos=new Ext.grid.GridPanel({
                            region  :'east',
                            title:'Adjuntos',
                            stripeRows  :true,
                            margins :'2 2 2 2',
                            width   :600,
                            border  :true,
                            tbar    :{
                                defaults	:{scope:this},
                                items   :[
                                    {xtype:'tbfill'},
                                    {text:'Adjuntar',iconCls:'agregar',handler:function(){
                                        var registro=Ext.getCmp('gridconsultas').getSelectionModel().getSelected();	
                                        if(!registro){
                                            msgALERTA('Aviso','Seleccione un reporte...');
                                            return false;
                                        }
					       if (registro.data['status']=='Finalizado' || registro.data['status']=='Cancelado' ){
                               		  msgALERTA('Aviso','El reporte ya esta finalizado o cancelado, NO puede adjuntar');
                                		  return false;
                            		}

                               	 		this.ventanaupload=new Ext.Window({
                            				title:'Adjuntar',
                            				bodyStyle	:'padding: 10px',
                            				width:600,
                            				layout	:'fit',
                            				height:200,
                            				modal:true,
                            				items:[
                                                new Ext.FormPanel({
                                                    id  :'paneladjunto',
                                    				fileUpload	:true,
                                    				bodyStyle	:'padding: 5px',
                                    				defaults	:{
                                    				    labelWidth  :250,
                                    					allowBlank	:false,
                                    					msgTarget	:'side'
                                    				},
                                    				items		:[
                                    					{xtype:'fileuploadfield',id:'userfile',anchor:'75%',emptyText:'Seleccione un archivo',fieldLabel:'Archivo',name:'userfile',buttonText:'',buttonCfg:{iconCls:'upload-icon'}},
                                                        {xtype:'textarea',maxLength:60,maxLengthText:'Este campo admite solo 60 caracteres',name:'descripcion',anchor:'75%',height:50,fieldLabel:'Descripcion del archivo'},
                                                        {xtype:'textfield',name:'folio_reporte',hidden:true,value:registro.get('id')}
                                    				],
                                    				buttons		:[
                                    					{text:'Subir',handler:function(){
                                    						if(Ext.getCmp('paneladjunto').getForm().isValid()){
                                    							Ext.getCmp('paneladjunto').getForm().submit({
                                    								url		:'ctradjuntar/upload',
                                    								waitMsg	:'Subiendo imagen...',
                                    								method	:'POST',
                                    								scope	:this,
                                    								success	:function(form,action){
                                    									var json=Ext.util.JSON.decode(action.response.responseText);
                                    									Ext.getCmp('paneladjunto').getForm().reset();
                                                                        Ext.getCmp('gridadjuntos').getStore().reload();
                                    									msgINFO('Informacion',json.mensaje);	
                                    								},
                                    								failure	:function(form,action){
                                    									var json=Ext.util.JSON.decode(action.response.responseText);
                                    									window.msgERROR('Error','Imposible adjuntar, '+json.mensaje);
                                    								}	
                                    							});
                                    						}else{
                                    							window.msgERROR('Error','Seleccione archivo a adjuntar por favor...')
                                    						}
                                    					}
                                    					,scope:this},{text:'Limpiar',handler:function(){Ext.getCmp('paneladjunto').getForm().reset()}}
                                    				]
                            			         })
                                            ]
                            				
                            			});
                            			this.ventanaupload.show();
                                    }}
                                ]
                            },
                            id  :'gridadjuntos',
                            store   :new Ext.data.JsonStore({
                                proxy   :new Ext.data.HttpProxy({
                                    api :{read:'ctradjuntar/consulta_adjuntos'},
                                    method  :'POST'
                                }),
                                root    :'data',
                                fields:[
                                    {name:'id'},
                                    {name:'hora'},
                                    {name:'fecha'},
                                    {name:'adjunto'},
                                    {name:'id_maagtic_reportes'},
                                    {name:'nombre_adjunto'},
                                    {name:'nombre_original'},
                                    {name:'observaciones'}
                                ]   
                            }),
                            columns :[
                                new Ext.grid.RowNumberer(),
                                {header:'Fecha',dataIndex:'fecha',width:75},
                                {header:'Adjunto',dataIndex:'adjunto',width:200},
                                {header:'Nombre archivo',dataIndex:'nombre_original',width:200,sortable:true},
                                {header:'Observaciones',dataIndex:'observaciones',width:500}
                            ]  
                        });
                        
			   this.gridadjuntos.on('rowdblclick',function(grid,index,e){
                var registro=grid.store.getAt(index);
                VerAdjunto(registro.data['nombre_adjunto'],registro.data['nombre_original']);
				
			   },this);	

                        var panelca=new Ext.Panel({
                           region   :'south',
                           border   :false,
                           height   :300,
                           layout   :'border',
                           items    :[
                           new Ext.grid.GridPanel({
                                region  :'center',
                                title:'Comentarios',
                                stripeRows  :true,
                                border  :true,
                                margins  :'2 2 2 2',
                                id  :'gridcomentarios',
                                store   :new Ext.data.JsonStore({
                                    proxy   :new Ext.data.HttpProxy({
                                        api :{read:'ctrregistro/consulta_comentarios'},
                                        method  :'POST'
                                    }),
                                    root    :'data',
                                    id : 'hora',
                                    fields:[
                                        {name:'id'},
                                        {name:'fecha'},
                                        {name:'hora'},
                                        {name:'comento'},
                                        {name:'descripcion'}
                                    ]   
                                }),
                                columns :[
                                    new Ext.grid.RowNumberer(),
                                    {header:'No.Reporte',dataIndex:'id',width:75,sortable:true},
                                    {header:'Fecha',dataIndex:'fecha',width:75,sortable:true},
                                    {header:'Hora',dataIndex:'hora',width:100},
                                    {header:'Comento',dataIndex:'comento',width:200},
                                    {header:'Descripcion',dataIndex:'descripcion',width:500}
                                ]  
                            }),
                            this.gridadjuntos
                           ]
                        });

                        var panelconsultas=new Ext.Panel({
                            layout  :'border',
                            border  :false,
                            items   :[gridconsultas,panelca]
                        });
                        
                        var winconsulta=new Ext.Window({ //     ventana principal de consultas
                            title  :'Consulta de reportes',
                            height  : 600,
                            maximizable :true,
                            minimizable :true,
                            width : 1000,
                            layout : 'fit',
                            id :'winconsulta',
                            resizable : true,
                            collapsible : true,
                            items   :[panelconsultas],
                            tbar :[
                                {xtype:'label',text:'No.Reporte'},
                                {xtype:'tbspacer'},
                                new Ext.form.NumberField({
                                    id  :'folio',
                                    name    :'folio',
                                    emptyText   :'0',
                                    width   :50,
                                    allowDecimals   :false,
                                    allowNegative   :false
                                }),
                                '-',
                                {xtype:'tbspacer'},
                                {xtype:'label',text:'Fecha inicial'},
                                {xtype:'tbspacer'},
                                new Ext.form.DateField({
                                    name:'fechainicial',
                                    id  :'fechainicial',
                                    width   :100,
                                    emptyText   :'Seleccione...',
                                    format  :'Y-m-d',
                                    value: new Date()
                                }),
                                {xtype:'tbspacer'},
                                {xtype:'label',text:'Fecha final'},
                                {xtype:'tbspacer'},
                                new Ext.form.DateField({
                                    name:'fechafinal',
                                    id  :'fechafinal',
                                    width   :100,
                                    emptyText   :'Seleccione...',
                                    format  :'Y-m-d',
                                    value: new Date()
                                }),
                                '-',
                                {xtype:'label',text:'Actividad'},
                                {xtype:'tbspacer'},
                                 new Ext.form.ComboBox({
                                  name : 'cactividad',
                                  id : 'cactividad',
                                  triggerAction:'all',   //trae los datos del query
                                  displayField : 'descripcion',
                                  valueField : 'id',
                                  emptyText : 'Seleccione ...',
                                  hiddenName : 'cactividad',
                                  editable : false,
                                  width : 300,                       
                                  fieldLabel :'Actividad ',
                                  store : new Ext.data.JsonStore({
                                    proxy : new Ext.data.HttpProxy({   //se especifica a que archivo php va a consultar
                                        api :{read : 'ctrregistro/catalogo_actividades_consultas'},
                                        method : 'post'
                                        }),
                                    root : 'data',
                                    fields : [
                                        {name :'id'},
                                        {name :'descripcion'} 
                                    ]
                                  }) //crear nuevo objeto store de datos   
                                }),
                                {text:'Reset',handler:function(){Ext.getCmp('cactividad').clearValue()}},
                                {xtype:'tbfill'},
                                '-',
                                {text:'Buscar',iconCls:'consultar',handler:function(){
                                    var mascara=new Ext.LoadMask(Ext.getBody(),{msg:'Buscando reportes, espere un momento...',store: Ext.getCmp('gridconsultas').getStore()});
                                    mascara.show();
                                    Ext.getCmp('gridconsultas').getStore().load({
                                        params:{
                                            folio:Ext.getCmp('folio').getValue(),
                                            fechainicial:Ext.getCmp('fechainicial').getValue(),
                                            fechafinal:Ext.getCmp('fechafinal').getValue(),
                                            cactividad:Ext.getCmp('cactividad').getValue(),
                                            ban:2
                                        }
                                    })                                    
                                }}
                            ],
                            listeners : {
                                close: function(){
                                    Ext.getCmp('winconsulta').destroy();
                                    Ext.getCmp('consulta').enable();      
                                }
                            }                                                    
                          });
                        winconsulta.show();
                        Ext.getCmp('gridconsultas').on('rowclick', function(grid, index, e){
                            var resultado = grid.store.getAt(index);
                            Ext.getCmp('gridcomentarios').getStore().load({
                                params: {id:resultado.id}
                            }); 
                            Ext.getCmp('gridadjuntos').getStore().load({
                                params: {id:resultado.id}
                            }); 
                        });
                        
                        //**** Graba comentario
                        Ext.getCmp('gridconsultas').on('rowdblclick',function (grid,index,e){//otra forma de listener... 
                            var resultado = grid.store.getAt(index);
				            if (resultado.data['status']=='Finalizado' || resultado.data['status']=='Cancelado' ){
                                msgALERTA('Aviso','El reporte ya esta finalizado o cancelado, NO puede agregar comentarios');
                                return false;
                            }
                                Fcomentario(resultado.id,Ext.getCmp('gridcomentarios'));          
                             });                     
                        //***********************
                        
                    }},
                    '-',
                     {text   :'&nbsp;&nbsp;&nbsp;Salir&nbsp;&nbsp;&nbsp;',iconCls:'salir',scale:'large',handler:function(){
                        Ext.Ajax.request({
                            url : 'ctrlogin/destruyesession',
                            success:function(){
                                window.location='http://intranet.educal.com.mx';
                            }
                        });
                      }},
                     {xtype:'tbfill'},
                     '-',
                     {text:'Administrador',iconCls:'admin',scale:'large',id:'administrador',handler:function(){
                        Administrador();
                     },scope:this}
                ]
            }
        })
        
        var Ventana=new Ext.Viewport({
            bodyStyle:'padding:5px',
            border  :true,
            height  :600,
            width   :900,
            layout  :'border',
            closable    :false,
            items   :[menu,datos,panelusuario],
            listeners   :{
                beforeshow:function(){
             				Ext.Ajax.request({
             					url		:'ctrlogin/validasession',
               					method	:'POST',
               					scope	:	this,
                                   
               					success	:function(response,request){
               						var json=Ext.util.JSON.decode(response.responseText);
               						if(json.existe==0){
               							acceso();
									if(tipbrowser=='Internet Explorer'){
                                    var WinBrowser=new Ext.Window({
                                        title:'Identificador de Navegador !!!',
                                        width:300,
                                        modal   :true,
                                        height:200,
                                        bodyStyle:'text-align:center;font-size:14px;padding:5px',
                                        html:'Para el correcto funcionamiento del sitio le sugerimos utilizar los siguientes navegadores:<br><br><img src="'+base_url+'/application/extjs/resources/images/Firefox.png"><img src="'+base_url+'/application/extjs/resources/images/Chrome.png">' 
                                    });
                                    WinBrowser.show();
                                }
					}
                                    else {
                                        Ext.getCmp('panelusuario').body.update(json.nombre);
                                        Ext.getCmp('cargainicial').getStore().load({
                                            params:{ban:1}
                                        });
					    if(json.id==null)
						Ext.getCmp('administrador').disable();

					    if(tipbrowser=='Internet Explorer'){
                                    	var WinBrowser=new Ext.Window({
                                        	title:'Identificador de Navegador !!!',
                                        	width:300,
                                        	modal   :true,
                                        	height:200,
                                        	bodyStyle:'text-align:center;font-size:14px;padding:5px',
                                        	html:'Para el correcto funcionamiento del sitio le sugerimos utilizar los siguientes navegadores:<br><br><img src="'+base_url+'/application/extjs/resources/images/Firefox.png"><img src="'+base_url+'/application/extjs/resources/images/Chrome.png">' 
                                    	});
                                    	WinBrowser.show();
                                	     }
                                    }  
                                    
               					}
                               });
                  }
            }
        });
       Ventana.show();
        //**** Finalizar solicitud

	Ext.getCmp('cargainicial').on('rowclick', function(grid,index,columna,e){
        	var registro=grid.store.getAt(index);
        	Ext.getCmp('panelobservacionesusuario').body.update(registro.get('observaciones'));
      });

       Ext.getCmp('cargainicial').on('rowdblclick',function (grid,index,e){//otra forma de listener... 
            var resultado = grid.store.getAt(index);
            var Winfinaliza = new Ext.Window({
                title  :'FINALIZAR solicitud',
                height  : 200,
                modal : true,
                width : 500,
                layout : 'fit',
                id :'Winfinaliza',
                resizable : true,                                                         
                tbar :[
                    {xtype:'tbfill'},
                    {text:'Confirmar ', iconCls:'guardar', handler:function(){
                        if (Ext.getCmp('formfinaliza').getForm().isValid())
                            Ext.getCmp('formfinaliza').getForm().submit({
                                url : 'ctrregistro/finalizasolicitud',
                                params : {id:resultado.id},
                                waitMsg : 'Finalizando solicitud ....',
                                success : function(){  
                                    Ext.getCmp('cargainicial').getStore().load({
                                        params: {ban:1}
                                    });  
                                    msgINFO('Informacion','Solicitud finalizada con exito');     
                                    Ext.getCmp('Winfinaliza').destroy();                                              
                                }
                            });
                        else
                            msgALERTA('Aviso','Favor de confirmar  ....');                                        
                    }},
                ],                          
                items :[  
                    new Ext.form.FormPanel({
                        id : 'formfinaliza',
                        frame : false,
                        border : false,
                        bodyStyle:'padding:5px',
                        items :[                                             
                            new Ext.form.TextArea({
                                name: 'finaliza',
                                id  : 'finaliza',
                                width : 300,
                                height: 100,
                                allowBlank : false,
                                blankText : 'Observaciones finales ',
                                fieldLabel : 'Observaciones finales '                                  
                            })                            
                        ]                                                                                                                   
                    })
                ]
            });
            Winfinaliza.show();          
             });         
    }
    
} /** fin de empacado */

Ext.onReady(app.informes.layout.init,app.informes.layout);
