 // 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.Aviso = Ext.extend(App.Module,{
	
	title: 'Quadro de Avisos',
	id: 'pedido-aviso',
	bodyBorder: false,
	layout: 'fit',
	iconCls: 'app-notice-16',
	moduleAction: 'aviso_action/',
	
	/**
	 * Inicializa o componente
	 */
	initComponent: function(){				
		//Chama o initComponent da super classe
		App.Pedido.Aviso.superclass.initComponent.apply(this, arguments);
		
	},//end of initComponent
		
	/**
	 * Cria o DataGrid de visualiza��o de Avisos
	 */
	createGrid : function(){
				
		//Cria o DataStore,
		this.store = new Ext.data.JsonStore({
                    proxy: new Ext.data.HttpProxy({
                            url: App.sysURL + this.moduleAction + 'findAll/',
                            method: 'POST'
                    }),
		    root: 'results',
		    idProperty: 'id',  
		    totalProperty: 'total',
		    fields: ['id','mensagem',{name: 'dt_aviso', type:'date', dateFormat:'Y-m-d'},'usuario_id','remetente','lido', 'aviso_id','destinatario']
		});

            var tpl = new Ext.XTemplate(
                '<tpl for=".">',
                '<div class="notice" id="{destinatario}-{aviso_id}">',
                '<div class="x-box-tl"><div class="x-box-tr"><div class="x-box-tc"></div></div></div>',
                '<div class="x-box-ml"><div class="x-box-mr"><div class="x-box-mc">',
                    '<h3 style="margin-bottom:5px;"><span class="aviso">{remetente} &nbsp;&nbsp;disse&nbsp;&nbsp; em&nbsp;&nbsp; {dt_aviso}:</span></h3>',
                    '<div class="x-form-bd" id="container">',
                                '<div class="x-form-item" style="font-size:14px;">{mensagem}</div>',
                                    '<tpl if="lido == 0">',
                                    '<div class="x-form-item" id="m"><a id="m" href="#" style="width: 250px;">',
                                    '<div class="mark-as-read" id="m">Marcar como lido</div></a>',
                                    '</tpl>',
                                    '<tpl if="lido == 1">',
                                    '<div class="x-form-item">',
                                    '<div class="read">Lido</div>',
                                    '</tpl>',
                                '</div>',
                                '<div class="x-form-item"></div>',
                    '</div>',
                '</div></div></div>',
                '<div class="x-box-bl"><div class="x-box-br"><div class="x-box-bc"></div></div></div>',
                '</tpl>',
                '<div class="x-clear"></div>'                
            );
                
            var panel = {
                    xtype: 'panel',
                    id: this.id + '-grid',
                    tbar: [
                        {
                                text: 'Novo',
                                iconCls: 'ui-add-icon',
                                tooltip: 'Adicionar novo registro',
                                handler: this.createRecord,
                                scope: this

                        }
                    ],
                    bodyStyle: 'padding:8px',
                    autoScroll: true,
                    items: new Ext.DataView({
                        store: this.store,
                        tpl: tpl,
                        autoHeight:true,
                        singleSelect: true,
                        overClass:'x-view-over',
                        itemSelector:'div.notice',
                        emptyText: '<b>Nenhum aviso para você</b>',
                        listeners:{
                          'click' : this.markRead,
                          scope: this
                        },
                        prepareData: function(data){
                            data.dt_aviso = data.dt_aviso.format("d/m/Y");
                            return data;
                        }
                    })

            };
		
            //Retorna o DataGrid criado
            return panel;
	},	
	
	/**
	 * Cria a janela e o formul�rio de edi��o de registro
	 */
	createForm : function(){
		//Cria o DataStore,
                this.usuarioStore = App.stores.Usuario;
                
		this.window = new Ext.Window({
			title: 'Aviso',
			iconCls: 'app-notice-16',
			width: 300,
			autoHeight: true,
			closeAction: 'hide',
			defaultButton: 0,
			items:[
				this.form = new Ext.form.FormPanel({
					baseCls: 'x-plain',
					labelAlign:'top',
					bodyStyle: 'padding:8px',
					items:[
						{
							xtype: 'hidden',
							name: 'id',
							value: 0
						},{
			                 name:'Quadro'
			                ,fieldLabel:'Enviar para'
			                ,xtype:'lovcombo'
			                ,triggerAction:'all'
			                ,mode:'remote'
			                ,store: this.usuarioStore
			                ,displayField:'nome'
			                ,valueField:'id'
                                        ,beforeBlur: Ext.emptyFn
			                ,hiddenName:'Quadro'
			                ,anchor: '98%'
			            },
						{
							xtype: 'datefield',
							fieldLabel: 'Expira em',
							allowBlank: false,
							name: 'dt_expiracao',
							anchor: '40%'
						},
						{
							xtype: 'textarea',
							fieldLabel: 'Mensagem',
							name: 'mensagem',
                                                        height: 100,
							anchor: '98%'
						}						
					]
				})
			],
			buttons:[
				{
					text:'<b>Salvar</b>',
					id: this.id + '-save-btn',
					scope: this
				},
				{
					text: 'Cancelar',
					scope: this,
					handler: this.cancel
				}
			]
		});
		
		this.window.on('show',function(win){
                    //Carrega o data store de fornecedores
                    //this.usuarioStore.load();

                    win.center();
		},this);
	},
	
	/**
	 * Renderiza a coluna Ativo
	 * @param {} value
	 */
	renderTipo : function(value){
		if (value == 'S')	
                    return 'Servi&ccedil;o';
		else if (value == 'P')
                    return 'Produto';
                else
                    return 'Taxa';
	},
	
	/**
	 * 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';
		}
	},

        markRead : function(dView, index, node, e){
            var id = Ext.fly(e.target).getAttribute('id');
            
            if (id == 'm'){
                e.target.className = 'mark-as-read-loading';
                var record = dView.getRecord(node);

                Ext.Ajax.request({
                        url: App.sysURL + this.moduleAction + 'markRead/',
                        method: 'POST',
                        params:{usuario_id: record.data.destinatario, aviso_id: record.data.aviso_id},
                        success : function(result){
                            Ext.ux.MessageBox.flash({
                                type: 'success',
                                msg: 'O aviso foi marcado como lido e removido do seu quadro!'
                            })
                            this.store.load();
                        },
                        scope : this
                });

            }
            
        },

	/**
	 * Confirma a inser��o do registro
	 *
	 */
	successInsert : function(){

            Ext.ux.MessageBox.flash({
                msg: 'O registro foi inserido com &ecirc;xito!',
                type: 'success'
            });

            this.form.enable();

            this.window.hide();
            this.store.load();

	}
});

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