﻿Ext.onReady(function() {
    Ext.QuickTips.init();
    Ext.form.Field.prototype.msgTarget = 'side';

    // Configura GRID
    ds = new Ext.data.Store({
           url: 'PropostasController.ashx',
           reader: new Ext.data.JsonReader(
                   { root: 'DataSet' }, 
                   [ 
                      {name: 'CartaoID'},
                      {name: 'FaturaID'},
                      {name: 'DataEmissao'},
                      {name: 'Descricao'},
                      {name: 'DataVencimento'},
                      {name: 'DataPagamento'},
                      {name: 'Valor'}
                   ]
           ) 
          });
          
      function formataPagamento(value) {
        if (value != '01/01/1900' && value != '1/1/1900')
          return value;
        else
          return "<a href='javascript:emiteBoleto();'><img src='../images/print.png' alt='Visualizar'></a>";
      }

      gridFaturas = new Ext.grid.GridPanel({
         id: 'pnl-grid-faturas',
         store: ds,
         loadMask: true,
         //resizeable: true,
         height: 310,
         //autoHeight: true,
         trackMouseOver: true,
         title: 'Faturas de Mensalidades',
         viewConfig: { emptyText: 'Nenhuma fatura.' },
         columns: [
		           { id: 'faturaIDColun', dataIndex: 'FaturaID', hidden: true },
		           { header: "Emissão", dataIndex: 'DataEmissao', width: 75 },
		           { id: 'descricaoColumn', header: "Descrição", dataIndex: 'Descricao', width: 200 },
		           { header: "Vencimento", dataIndex: 'DataVencimento', width: 75 },
                   { header: "Valor", dataIndex: 'Valor', width: 75},
                   { header: "Pagamento", dataIndex: 'DataPagamento', width: 75, renderer: formataPagamento  }
                  ],
		  autoExpandColumn: 'descricaoColumn'
      });
        
    var btnCancelar = {
        scope  : this,
        text   : 'Voltar',
        handler: function() { document.location=urlBase }
    };
    
    var btnOk = {
        scope  : this,    
        text   : 'Consultar',    
        handler: function() { gravarDados(); }
    }
    Ext.applyIf(btnOk, ComproCard.Buttons.Ok);    
    Ext.applyIf(btnCancelar, ComproCard.Buttons.Cancelar);      
    
    var txtCPF    = new Ext.ux.colfield( form, 'cpf', 'CPF', 'txtCPF', 110, { allowBlank: false } );
    var txtCartao = new Ext.ux.colfield( form, 'card', 'Cartão', 'txtCartao', 145, { allowBlank: false } );
    
    var form = new Ext.FormPanel({
        title: 'Emitir faturas para pagamento de mensalidades',
        frame: true,
        width: 520,
        autoHeight: true,
        id: 'frm-faturas',
        url: 'PropostasController.ashx', 
        method: 'post',
        labelWidth: 80,
        defaultType: 'textfield',
        cls: 'x-panel-mc vc-panel-mc',
        items: [{ 
                  xtype: 'fieldset',                
                  title: 'Dados do Cartão/Associado',
                  defaultType: 'textfield',                  
                  autoHeight: true,
                  items: [ txtCPF,
                           txtCartao
                         ]
                 },
                 gridFaturas
                 
              ],
              buttons: [btnOk, btnCancelar]
    });

    emiteBoleto = function() {
       var dados = gridFaturas.getSelectionModel().getSelected();
       window.open('boleto.aspx?cpf=' + txtCPF.getValue() + '&fid=' + dados.get("FaturaID"));
    }

    resetaForm = function() {
    }
             
    atualizaCampos = function(dados) {
      ds.load( { params: {acao: 'faturas', txtCartao: Ext.getCmp('txtCartao').getValue() } } );
      
    }

    gravarDados = function() {
        var form = Ext.getCmp('frm-faturas').getForm();        
        if (!form.isValid())
	        Ext.Msg.show({ title    : 'Erro',
                           msg      : 'Favor corrigir o(s) erro(s) encontrado(s).',
                           buttons  : Ext.Msg.OK
                         });
	    else 
	    {
	      resetaForm();
	      form.submit({waitMsg: 'Aguarde. Consultando informações....', params: { acao: 'verify' },
	                   url: 'PropostasController.ashx',
	                   failure: function(frm, action) {
                                   Ext.MessageBox.alert('Erro', action.result.errorInfo);
                                },
    	                       
	                   success: function(frm, action) {
	                               if (!action.result)
   	                                 Ext.MessageBox.alert('ERRO', 'Erro na comunicação com o servidor.');
   	                               else
   	                               {
	                                 atualizaCampos(action.result);
	                               }
	                            }
	                  });
	    }
	}

    ComproCard.Layout.init();
    var mainPanel = Ext.getCmp('pnl-main');
    mainPanel.add(form);
    mainPanel.doLayout();
    ComproCard.Layout.removeLoading();
  	//Ext.get("frm-faturas").center();
});

