 // vim: sw=4:ts=4:nu:nospell:fdc=4
 /*global Ext, App */
 /**
 * Componente de �rea de administra��o de itens de solicita��o
 *
 * @author Ot�vio Augusto
 * @copyright (c) 2009, by Ot�vio Augusto
 * @company Net On - Solu��es Tecnol�gicas
 * @date 7 de Setembro 2009
 *
 */

//Define o namespace
Ext.ns('App.Pedido');

App.Pedido.Pedido = Ext.extend(App.Module,{
	
	title: 'Gerenciamento de Pedidos',	
	id: 'pedido-pedido',	
	bodyBorder: false,
	layout: 'fit',
	iconCls: 'app-solicitacao-16',
	moduleAction: 'pedido_action/',	
	
	/**
	 * Inicializa o componente
	 */
	initComponent: function(){				
		//Chama o initComponent da super classe
		App.Pedido.Pedido.superclass.initComponent.apply(this, arguments);
		
		this.orcamentos = new Array();
		this.orcamentosC = 0;
		
		this.on('beforeinsert',this.fixTipo,this);
		this.on('beforeupdate',this.fixTipo,this);
		this.on('beforeedit',this.load,this);
		this.on('beforecreate',this.resetWindow, this);
			
		 Ext.util.Format.brMoney = function(v){
	            v = (Math.round((v-0)*100))/100;
	            v = (v == Math.floor(v)) ? v + ".00" : ((v*10 == Math.floor(v*10)) ? v + "0" : v);
	            v = String(v);
	            var ps = v.split('.');
	            var whole = ps[0];
	            var sub = ps[1] ? '.'+ ps[1] : '.00';
	            var r = /(\d+)(\d{3})/;
	            while (r.test(whole)) {
	                whole = whole.replace(r, '$1' + ',' + '$2');
	            }
	            v = whole + sub;
	            if(v.charAt(0) == '-'){
	                return '-R$ ' + v.substr(1);
	            }
	            return "R$" +  v ;
		};
		
		
	},//end of initComponent
		
	/**
	 * Cria o DataGrid de visualiza��o de Grupos
	 */
	createGrid : function(){

		var panel = {
                    id: this.id + '-grid',
                    xtype: 'tabpanel',
                    activeTab: 0,
                    items:[
                        {
                            xtype: 'pedido-situacao-criado',
                            id: 'pedido-situacao-criado',
                            parent: this
                        },
                        {
                            xtype: 'pedido-situacao-autorizado',
                            id: 'pedido-situacao-autorizado',
                            parent: this
                        },
                        {
                            xtype: 'pedido-situacao-nao-autorizado',
                            id: 'pedido-situacao-nao-autorizado',
                            parent: this
                        },
                        {
                            xtype: 'pedido-situacao-entregue',
                            id: 'pedido-situacao-entregue',
                            parent: this
                        }

                    ]
		};
		
		//Retorna o DataGrid criado
		return panel;
	},	
	
	/**
	 * Cria a janela e o formul�rio de edi��o de registro
	 */
	createForm : function(){
		var typeData = [
            ['S','Servi\u00e7o'],
            ['P','Produto']
		];
		                
		//Cria um simplestore de tipos 
		var typeStore = new Ext.data.SimpleStore({
			fields: ['id', 'tipo'],
			data: typeData
		});
		
		//Cria o DataStore de lista de produtos
		this.listaStore = new Ext.data.JsonStore({
	    	proxy: new Ext.data.HttpProxy({ 
	    		url: App.sysURL + 'item_action/findAll/',
	    		method: 'POST'
	    	}),
		    root: 'results',
		    idProperty: 'id',  
		    totalProperty: 'total',
		    fields: ['descricao','id']
		});		
		
		//Cria o DataStore de items
		this.orcamentoStore = new Ext.data.JsonStore({
	    	proxy: new Ext.data.HttpProxy({ 
	    		url: App.sysURL + 'orcamento_action/findAll/',
	    		method: 'POST'
	    	}),
		    root: 'results',
		    idProperty: 'id',  
		    totalProperty: 'total',
		    fields: ['id','pedido_id','empresa_id','selected']
		});
		
		/* Desativado em 02/02/10 por Otávio
		this.empresaStore = new Ext.data.JsonStore({
	    	proxy: new Ext.data.HttpProxy({ 
	    		url: App.sysURL + '/empresa_action/findAll/',
	    		method: 'POST'
	    	}),
		    root: 'results',
		    idProperty: 'id',  
		    totalProperty: 'total',
		    fields: ['razaosocial', 'id']
		});*/
                this.empresaStore = App.stores.Empresa;
		
		this.window = new Ext.Window({
			title: 'Pedido',
			iconCls: 'app-solicitacao-16',
			width: 600,
			autoHeight: true,
			closeAction: 'hide',
			defaultButton: 0,
			items:[
				this.form = new Ext.form.FormPanel({
					baseCls: 'x-plain',
					labelAlign:'top',
                                        autoHeight: true,
					items:[
						{
							xtype: 'hidden',
							name: 'id'
						},
						{
							xtype: 'tabpanel',
							activeTab: 0,
							enableTabScroll: true,
							id : this.id + '-tab-panel',
							items:[
							       {
							    	   xtype: 'panel',
                                                                   autoHeight: true,
							    	   title: 'Justificativa',
							    	   bodyStyle: 'padding:8px;',
							    	   baseCls: 'x-plain',
							    	   items: [
												{
													xtype: 'container',
													layout: 'column',
													defaults: {
														layout: 'form'
													},
													items:[
													       {
													    	   xtype: 'container',
													    	   columnWidth: .3,
													    	   items:[
													    	          {
													    	        	  xtype: 'datefield',
													    	        	  //readOnly: true,
													    	        	  fieldLabel: 'Data do pedido',
													    	        	  name: 'dt_pedido'													    	        		  
													    	          }
													    	   ]
													       },
													       {
													    	   xtype: 'container',
													    	   columnWidth: .7,
													    	   items:[
													    	          {
													    	        	  xtype: 'combo',
													    	        	  fieldLabel: 'Tipo de pedido',
													    	        	  hiddenName: 'tipo',
													    	        	  triggerAction: 'all',
													    	        	  mode: 'local',
													    	        	  allowBlank: false,
													    	        	  store: typeStore,
													    	        	  editable: false,
													    	        	  /*listeners:{
													    	        	  	'select' : function(owner){
													    	        	  		owner.readOnly = true;
													    	          		}
													    	          	  },*/
													    	        	  valueField: 'id',
													    	        	  displayField: 'tipo'
													    	          }
													    	   ]
													       }
													       
													      
													]
												
									            },
									            {
									            	xtype: 'container',
									            	layout: 'form',
									            	items:[
									            	       {
									            	    	   xtype: 'textfield',
									            	    	   anchor: '98%',
									            	    	   name: 'identificacao',
									            	    	   allowBlank: false,
									            	    	   fieldLabel: 'Identifica&ccedil;&atilde;o deste pedido'
									            	       }
									            	]
									            },							    	           									            
									            {
									            	xtype: 'container',
									            	layout: 'form',
									            	items:[
									            	       {
									            	    	   xtype: 'textarea',
									            	    	   anchor: '98%',
									            	    	   name: 'justificativa',
									            	    	   allowBlank: false,
									            	    	   fieldLabel: 'Justificativa',
									            	    	   height: 80
									            	       },
									            	       {
									            	    	   xtype: 'textarea',
									            	    	   anchor: '98%',
									            	    	   id: 'txt-observacao',
									            	    	   name: 'observacao',
									            	    	   emptyText: 'Somente pessoas autorizadas',
									            	    	   allowBlank: false,
									            	    	   fieldLabel: 'Observa&ccedil;&atilde;o (Autoriza&ccedil;&atilde;o / N&atilde;o autoriza&ccedil;&atilde;o)',
									            	    	   height: 80,
									            	    	   disabled: true
									            	       }									            	       
									            	]
									            }							    	           
							    	   ]
							       },
							       this.lista = new Pedido.Pedido.Lista(),
							      {
							    	  title: 'Novo or&ccedil;amento',
							    	  iconCls: 'ui-page-add-icon',
							    	  id: 'tab-new-orcamento',
							    	  listeners:{
							    	   	  'show' : function(){
							    	   		  this.createOrcamento();
							       		  },
							    	   	  scope: this
							       	  }
							    		  
							      }
							       

							]	
						}
					]
				})
			],
			buttons:[
		         {
		        	 text: '<b>Autorizar</b>',
		        	 id: this.id + '-accept-btn',
		        	 scope: this,
		        	 hidden: true,
		        	 handler: this.accept
		         },		        
		         {
		        	 text: 'N&atilde;o autorizar',
		        	 id: this.id + '-decline-btn',
		        	 scope: this,
		        	 hidden: true,
		        	 handler: this.decline
		         },
		         {
		        	 text: '<b>Gerar ordem</b>',
		        	 id: this.id + '-ordem-btn',
		        	 scope: this,
		        	 hidden: true,
		        	 handler: this.report
		         },		        
		         {
		        	 text: 'Confirmar recebimento / execu&ccedil;&atilde;o',
		        	 id: this.id + '-concluido-btn',
		        	 scope: this,
		        	 hidden: true,
		        	 handler: this.finalize
		         },		         
				{
					text:'<b>Salvar</b>',
					id: this.id + '-save-btn',
					scope: this
				},
				{
					text: 'Cancelar',
					scope: this,
					handler: this.cancel
				}
			],
			listeners: {
				'hide' : function(){
                                    this.resetWindow();
				},
				scope: this
			}
		});

                this.applySecurity();
                
		this.window.on('show',function(win){
			//win.center();
		},this);
	},

        /**
         * Remove acessos não autorizados do usuário
         */
        applySecurity : function(){
            if (App.data.user.can_autorizar != '1'){
                if (Ext.getCmp(this.id + '-accept-btn'))
                    Ext.getCmp(this.id + '-accept-btn').destroy();
                if (Ext.getCmp(this.id + '-decline-btn'))
                    Ext.getCmp(this.id + '-decline-btn').destroy();

            }
            
        },
	
	/**
	 * Renderiza a coluna Ativo
	 * @param {} value
	 */
	renderTipo : function(value){
		if (value == 'S')	
			return 'Servi&ccedil;o';
		else
			return 'Produto';
	},
	
	/**
	 * Evento a ser executado antes da inser��o
	 * @param {} module
	 */
	fixTipo : function(module){
		//Se a propriedade ativo n�o estiver marcada, define seu valor como zero
		if (!module.params.tipo){
			module.params.tipo = 'S';
		}
	},
	
	/**
	 * Cria o painel de or�amentos
	 */
	createOrcamento : function(sender, data){
		if (!data){
                    Ext.Msg.show({
                       title: 'Aten&ccedil;&atilde;o',
                       msg: 'Ap&oacute;s adicionar um or&ccedil;amento, <b>n&atilde;o ser&aacute; mais poss&iacute;vel adicionar, remover ou alterar nenhum item na lista</b>. Deseja realmente faz&ecirc;-lo agora?',
                       buttons: Ext.MessageBox.YESNO,
                       icon: Ext.MessageBox.WARNING,
                       width:380,
                       fn: function(btn){                            
                            if (btn == 'yes'){
                                this.doCreateOrcamento(sender, data);
                           }else{
                               var tab = Ext.getCmp(this.id + '-tab-panel');
                               tab.setActiveTab(1);
                           }
                       },
                       scope: this
                    });
                    
                }else
                    this.doCreateOrcamento(sender, data);
	},

        doCreateOrcamento : function(sender, data){
            var tab = Ext.getCmp(this.id + '-tab-panel');
            var i = tab.items.getCount()-2;

            this.orcamentos[this.orcamentosC] =  new Pedido.Pedido.Orcamento({
                    xtype: 'pedido-orcamento',
                    title: 'Or&ccedil;amento '+ (this.orcamentosC + 1),
                    pedido: this,
                    data: data,
                    listeners: {
                            'close': function(){
                                    this.orcamentosC--;
                                    this.orcamentos[(this.orcamentosC)] = undefined;
                                    //console.debug(this.orcamentos);
                            },
                            scope: this
                    }
            });

            tab.insert(i+1,this.orcamentos[(this.orcamentosC)]);
            this.orcamentosC++;

            i = tab.items.getCount()-2;
            tab.setActiveTab(i);

            //Desabilita botões da lista
            Ext.getCmp('lista-add-item').disable();
            Ext.getCmp('lista-delete-item').disable();
            
        },
	
	/**
	 * Efetua a valida��o do formul�rio
	 */	
	validate : function(){
		if (!this.form.form.isValid()){
			Ext.MessageBox.show({
				title:'Aten&ccedil;&atilde;o',
			    msg: 'Os campos marcados em "Justificativa" s&atilde;o obrigat&oacute;rios!',
			    buttons: Ext.Msg.OK,
			    icon: Ext.MessageBox.ERROR				
			});			
			return false;
		}
		
		if (this.lista.store.getCount() <= 0){
			Ext.MessageBox.show({
				title:'Aten&ccedil;&atilde;o',
			    msg: 'A "Lista do pedido" est&aacute; vazia!',
			    buttons: Ext.Msg.OK,
			    icon: Ext.MessageBox.ERROR				
			});			
			return false;			
		}

		if (this.orcamentos.length <= 0){
			Ext.MessageBox.show({
				title:'Aten&ccedil;&atilde;o',
			    msg: 'Nenhum or&ccedil;amento foi criado!',
			    buttons: Ext.Msg.OK,
			    icon: Ext.MessageBox.ERROR				
			});			
			return false;			
		}
		
		try{
		var orcamento = null;
		for (i = 0; i < this.orcamentos.length; i++){
			orcamento = this.orcamentos[i];
			if (orcamento.cmbFornecedor.getValue() == ''){
				Ext.MessageBox.show({
					title:'Aten&ccedil;&atilde;o',
				    msg: 'O "Prestador / Fornecedor" do Or&ccedil;amento ' + (i + 1) + ' n&atilde;o foi informado!' ,
				    buttons: Ext.Msg.OK,
				    icon: Ext.MessageBox.ERROR				
				});			
				return false;
			}
			
			if (orcamento.store.sum('total') == 0){
				Ext.MessageBox.show({
					title:'Aten&ccedil;&atilde;o',
				    msg: 'O pre&ccedil;o do Or&ccedil;amento '+ (i+1) + ' n&atilde;o pode ser igual a zero!' ,
				    buttons: Ext.Msg.OK,
				    icon: Ext.MessageBox.ERROR				
				});			
				return false;				
			}
			
			if (orcamento.condicaoPanel.store.getCount() <= 0){
				Ext.MessageBox.show({
					title:'Aten&ccedil;&atilde;o',
				    msg: 'O Or&ccedil;amento '+ (i+1) + ' n&atilde;o possui nenhuma parcela lan&ccedil;ada!' ,
				    buttons: Ext.Msg.OK,
				    icon: Ext.MessageBox.ERROR				
				});			
				return false;				
			}
		}
		}catch(e){}
		
		return true;
	},
	
	/**
	 * Submete os dados preenchidos para camada de dom�nio
	 */
	insertRecord : function(button){

		if (this.validate()){
                       Ext.ux.Loader.start({sender: button, waitingText: 'Salvando...'});

                        var params = {};
			params = this.form.form.getValues();			
			params.Lista = this.lista.getValues();
			
			var orc = new Array();
			for (j = 0; j < this.orcamentos.length; j++){
				orc[j] = this.orcamentos[j].getValues();
			}
			
			params.Orcamento = Ext.encode(orc);
			
			this.params = params;
			
			Ext.Ajax.request({
			   url: App.sysURL + this.moduleAction + 'save/',
			   success: function(){                               
                               Ext.ux.MessageBox.flash({
                                   msg: 'O registro foi inserido com &ecirc;xito!',
                                   type: 'success'
                               });
                               
                               Ext.ux.Loader.stop(button);
                               Ext.getCmp('pedido-situacao-criado').store.load();
                               this.window.hide();
                           },
			   failure: this.failureInsert,
			   params: this.params,
			   scope: this			
			});
			
			
		}
	},
	
	renderSituacao : function(v){
		switch(v){
			case 'C':
				return 'Aguardando autoriza&ccedil;&atilde;o';
			break;
			case 'D':
				return 'Autorizado';
			break;
			case 'I':
				return 'N&atilde;o autorizado';
			break;
			case 'E':
				return 'Conclu&iacute;do';
			break;
			
		}
	},
	
	/**
	 * Efetua o carregamento da lista de pedidos e dos or�amentos
	 */
	load : function(sender, record){
		var tab = Ext.getCmp(this.id + '-tab-panel');		

                this.loaderTarget = this.window;
                Ext.ux.Loader.start({sender: this.window, waitingText: 'Carregando...'});
                
		Ext.getCmp(this.id+'-save-btn').hide();
		
		//Oculta a aba de cria��o de novo or�amento
		var newOrcamento = Ext.getCmp('tab-new-orcamento');
		tab.hideTabStripItem(newOrcamento);
		
		if (record.data.situacao == "C"){
			this.changeButtonVisibility(this.id+'-accept-btn', true);
                        this.changeButtonVisibility(this.id+'-decline-btn', true);
		}
		
		//Esconde os bot�es de aceita��o e n�o-aceita��o quando a situa��o � I
		if (record.data.situacao == 'I'){
			this.changeButtonVisibility(this.id+'-accept-btn', false);
                        this.changeButtonVisibility(this.id+'-decline-btn', false);
		}
		
		//Se o pedido foi aceito
		if (record.data.situacao == "D"){

			//Exibe os bot�es de gerar ordem e de confirma��o de execu��o/recebimento
			this.changeButtonVisibility(this.id+'-ordem-btn', true);
                        this.changeButtonVisibility(this.id+'-concluido-btn', true);

			//Oculta os bot�es de aceita��o e n�o-aceita��o
			this.changeButtonVisibility(this.id+'-accept-btn', false);
                        this.changeButtonVisibility(this.id+'-decline-btn', false);

		}
		
		//Se o pedido foi encerrado
		if (record.data.situacao == "E"){
			//Exibe os bot�es de gerar ordem e de confirma��o de execu��o/recebimento
			this.changeButtonVisibility(this.id+'-ordem-btn', false);
                        this.changeButtonVisibility(this.id+'-concluido-btn', false);

			//Oculta os bot�es de aceita��o e n�o-aceita��o
			this.changeButtonVisibility(this.id+'-accept-btn', false);
                        this.changeButtonVisibility(this.id+'-decline-btn', false);

		}
		
		
		Ext.getCmp('txt-observacao').enable();
		
		
		//Recupera o id do pedido
		this.pedido = record.data.id;
		
		//Carrega a lista do pedido
		this.lista.load(this.pedido);
		
		//Carrega a lista de or�amentos
		this.orcamentoStore.on('load',this.loadOrcamento,this);
		this.orcamentoStore.load({params:{pedido_id: this.pedido}});
		
	},

        /**
         * Altera o estado de um botão, habilitado desabilitado
         * @param String id ID do botão
         * @param Boolean visible estado do botão
         */
        changeButtonVisibility : function(id, visible){
            if (Ext.getCmp(id)){
                Ext.getCmp(id).setVisible(visible);
            }
        },
	
	loadOrcamento : function(store){
		this.orcamentosC = 0;
		for (var i = 0; i < store.data.length; i++){
			record = store.data.items[i];
			this.createOrcamento(this,record.data);
		}

                Ext.ux.Loader.stop(this.loaderTarget);
                delete(this.loaderTarget);
	},
	
	resetWindow : function(){
		//Mostra a aba de cria��o de novo or�amento		
		var tab = Ext.getCmp(this.id + '-tab-panel');				
		var newOrcamento = Ext.getCmp('tab-new-orcamento');
		tab.unhideTabStripItem(newOrcamento);
                tab.activate(0);
		
                //Remove os orçamentos
                var tab = Ext.getCmp(this.id + '-tab-panel');
                var numOrc = this.orcamentos.length;
                for (j = 0; j <= (numOrc); j++){
                    tab.remove(this.orcamentos[j]);
                }

                this.orcamentos = [];

		this.changeButtonVisibility(this.id+'-save-btn', true);
		this.changeButtonVisibility(this.id+'-accept-btn', false);
		this.changeButtonVisibility(this.id+'-decline-btn', false);
		this.changeButtonVisibility(this.id+'-ordem-btn', false);
		this.changeButtonVisibility(this.id+'-concluido-btn', false);

                Ext.getCmp('lista-add-item').enable();
                Ext.getCmp('lista-delete-item').enable();
		
		this.lista.store.removeAll();
		this.orcamentosC = 0;
		Ext.getCmp('txt-observacao').disable();
	},
	
	accept : function(button){
		Ext.MessageBox.confirm('Confirme','Aprovar este pedido?',
				function(btn){
					if (btn == 'yes'){
                                               Ext.ux.Loader.start({sender: button, waitingText: 'Autorizando...'});

						//Request an action to verify if exists a session started
						Ext.Ajax.request({
							url: App.sysURL + 'pedido_action/accept/',
							method: 'POST',
							params:{id: this.pedido, observacao: Ext.getCmp('txt-observacao').getValue()},
							success : function(result){
								eval('var action = ' + result.responseText);					
								if (action.success == 'true'){

                                                                       Ext.ux.MessageBox.flash({
                                                                           msg: 'O registro foi atualizado com &ecirc;xito!',
                                                                           type: 'success'
                                                                       });
                                                                        Ext.ux.Loader.stop(button);
									this.window.hide();
									this.loadStores();
								}else{
								}					
							},
							scope : this
						});
					}					
				},this
		);
		
	},
	
	decline : function(button){
		Ext.MessageBox.confirm('Confirme','N&atilde;o aprovar este pedido?',
				function(btn){
					if (btn == 'yes'){
                                               Ext.ux.Loader.start({sender: button, waitingText: 'Negando pedido...'});

						//Request an action to verify if exists a session started
						Ext.Ajax.request({
							url: App.sysURL + 'pedido_action/decline/',
							method: 'POST',
							params:{id: this.pedido, observacao: Ext.getCmp('txt-observacao').getValue()},
							success : function(result){
								eval('var action = ' + result.responseText);					
								if (action.success == 'true'){                                                                       
                                                                       Ext.ux.MessageBox.flash({
                                                                           msg: 'O registro foi atualizado com &ecirc;xito!',
                                                                           type: 'success'
                                                                       });
                                                                        Ext.ux.Loader.stop(button);
                                                                        this.window.hide();
									this.loadStores();
								}else{
								}					
							},
							scope : this
						});
					}					
				},this
		);
		
	},
	
	/**
	 * Chama m�todo remoto para a confirma��o do recebimento/execu��o da lista
	 * do pedido
	 */
	finalize : function(button){
		Ext.MessageBox.confirm('Confirme','Confirmar execu&ccedil;&atilde;o/recebimento deste pedido?',
				function(btn){
					if (btn == 'yes'){
                                               Ext.ux.Loader.start({sender: button, waitingText: 'Confirmando recebimento...'});

						//Request an action to verify if exists a session started
						Ext.Ajax.request({
							url: App.sysURL + 'pedido_action/finalize/',
							method: 'POST',
							params:{id: this.pedido, observacao: Ext.getCmp('txt-observacao').getValue()},
							success : function(result){
								eval('var action = ' + result.responseText);					
								if (action.success == 'true'){
                                                                       Ext.ux.Loader.stop(button);
                                                                       Ext.ux.MessageBox.flash({
                                                                           msg: 'O registro foi atualizado com &ecirc;xito!',
                                                                           type: 'success'
                                                                       });

									this.window.hide();
									this.loadStores();
								}else{
								}					
							},
							scope : this
						});
					}					
				},this
		);
		
	},
	
	/**
	 * Chama relat�rio de pedidos
	 */
	report : function(){
		window.open(App.sysURL + 'pedido_action/report/' + this.pedido,'blank');
	},

        loadStores : function(){
            Ext.getCmp('pedido-situacao-criado').store.load();
            Ext.getCmp('pedido-situacao-autorizado').store.load();
            Ext.getCmp('pedido-situacao-nao-autorizado').store.load();
            Ext.getCmp('pedido-situacao-entregue').store.load();
        },

	/**
	 * Abre a janela do formul�rio para a inser��o
	 */
	editRecord : function(sender){
		//Recupera o registro selecionado
		var record = this.getSelectedRecord(sender);

		//Se o registro n�o existir,
		if (!record){
                   Ext.ux.MessageBox.flash({
                       msg: 'Nenhum registro foi selecionado!',
                       type: 'warning'
                   });
                }else{
			if (!this.window)
				//Cria a mesma
				this.createForm();

                                //Exibe a janela de edi��o
                                this.window.show();

                                //Aciona o evento
                                this.fireEvent('beforeedit',this,record);

			try{
				Ext.getCmp(this.id+'-save-btn').handler = this.updateRecord;
			}catch(e){}

			//Seta o formul�rio com os valores do registro selecionado
                        this.form.form.setValues(record.data);
                }


	},

	/**
	 * Recupera o registro selecionado em um data grid
	 */
	getSelectedRecord : function(sender){
            var grid = sender;

            //Recupera o SelectionModel do grid
            var sm = grid.getSelectionModel();

            //Verifica se o grid possui a propriedade selection
            if (sm.selection){
                    return sm.selection.record;
            }else{
	    	//Verifica se o grid possui o m�todo getSelected()
	    	try{
	    		return sm.getSelected();
	    	}catch(e){
	    		return false
	    	}
            }

	}


	
});

//Registra o novo componente
Ext.reg('pedido-pedido',App.Pedido.Pedido);
