﻿var app = {
    download: function(fname, uid) {
        this.iframe.dom.src = 'download.aspx?fname=' + fname;
        this.store.getById(uid).data.downloaded = true;
        this.store.fireEvent('datachanged', this.store);
        
    },
    rpWinShow: function() {
        this.rpWin.show();
    },
    cpWinShow: function() {
        this.cpWin.show();
    },
    loginResponse: function(form,action) {
        this.loginMessage.body.update('');
        this.main.layout.setActiveItem(1);
        this.store.load();
    },
    loginResponseFailure: function(form,action) {
        if(action.result)
            this.loginMessage.body.update('Login fallito. Username e/o password non validi');
    },
    login: function() {
        if(this.loginPanel.form.isValid())
            this.loginMessage.body.update('Connessione in corso....');
        this.loginPanel.form.submit({
            url: 'Login.aspx',
            success: this.loginResponse,
            failure: this.loginResponseFailure,
            scope: this
        });
    },
    logout: function() {
        Ext.getCmp('fldPassword').setRawValue('');
        this.main.layout.setActiveItem(0);
    },
    recupera: function() {
        if(this.rpPanel.form.isValid())
            this.rpMessage.body.update('Richiesta in corso....');
        this.rpPanel.form.submit({
            url: 'RecuperoPassword.aspx',
            success: this.recuperaResponse,
            failure: this.recuperaResponseFailure,
            scope: this
        });
    },
    recuperaResponse: function(form,action) {
        this.rpMessage.body.update('E&#39; stato inviato un email all&#39;indirizzo specificato.');
    },
    recuperaResponseFailure: function(form,action) {
        if(action.result)
            this.rpMessage.body.update('Nessun utente associato a questo indirizzo email');
    },
    cambia: function() {
        if(this.cpPanel.form.isValid())
            this.cpMessage.body.update('Richiesta in corso....');
        this.cpPanel.form.submit({
            url: 'CambioPassword.aspx',
            success: this.cambiaResponse,
            failure: this.cambiaResponseFailure,
            scope: this
        });
    },
    cambiaResponse: function(form,action) {
        this.cpMessage.body.update('La password è stata cambiata con successo.');
    },
    cambiaResponseFailure: function(form,action) {
        if(action.result)
            this.cpMessage.body.update('Impossibile cambiare la password. Controllare di aver inserito correttamente la vecchia password.');
    },
    init: function(logged) {
        this.autoLogin = logged;
        Ext.QuickTips.init();
        Ext.form.Field.prototype.msgTarget = 'side';

        this.iframe = Ext.DomHelper.append(document.body, {
                tag: 'iframe',
                frameBorder: 0,
                width: 0,
                height: 0,
                css: 'display:none;visibility:hidden;height:1px;'
            }, true);

        this.store = new Ext.data.JsonStore({
            url: 'Fatture.aspx',
            totalProperty: "count",
            root: 'records',
            id:'uid',
            sortInfo: {field: "numero", direction: "DESC"},
            baseParams: {todownload:false},
            fields: ['uid','file', 'downloaded', 'numero', {name:'data', type:'date'}]
        });
        this.cpWin = new Ext.Window({
    	    title: 'Cambio password',
            layout: 'fit',
            width: 420,
            height: 200,
            closeAction :'hide',
            plain: true,
            modal: true,
            draggable: false,
            resizable: false,
            items: {
                xtype:'panel',
                border:false,
		            bbar: new Ext.Toolbar({
		                buttons:['->',{
			                text: 'Invia richiesta',
			                style: 'left: 100px;',
       				        handler: this.cambia,
			                scope: this
		                },{
			                text: 'Chiudi',
			                style: 'left: 100px;',
        				    handler: function() {this.cpWin.hide();},
			                scope: this
		                }]
		            }),
                items: this.cpPanel = new Ext.form.FormPanel({
    		        style: 'padding:5px 5px 5px 5px',
			        layout: 'form',
			        frame: false,
			        width: 400,
			        defaultType: 'textfield',
			        border: false,
			        labelWidth: 150,
                    items: [{
				        fieldLabel: 'Vecchia password',
				        name: 'old',
					    inputType: 'password',
				        width: 200,
				        allowBlank:false
				    },{
				        fieldLabel: 'Nuova password',
				        name: 'pwd',
					    inputType: 'password',
				        width: 200,
				        allowBlank:false
				    },{
				        fieldLabel: 'Conferma password',
				        name: 'confirm',
					    inputType: 'password',
				        width: 200,
				        allowBlank:false
				    }, this.cpMessage = new Ext.Panel({
			            width:370,
			            border: false
			        })]
                })
            }
        });

        this.rpWin = new Ext.Window({
    	    title: 'Recupero password',
            layout: 'fit',
            width: 400,
            height: 110,
            closeAction :'hide',
            plain: true,
            modal: true,
            draggable: false,
            resizable: false,
            items: {
                xtype:'panel',
                border:false,
		            bbar: new Ext.Toolbar({
		                buttons:['->',{
			                text: 'Invia richiesta',
			                style: 'left: 100px;',
       				        handler: this.recupera,
			                scope: this
		                },{
			                text: 'Chiudi',
			                style: 'left: 100px;',
        				    handler: function() {this.rpWin.hide();},
			                scope: this
		                }]
		            }),
                items: this.rpPanel = new Ext.form.FormPanel({
    		        style: 'padding:5px 5px 5px 5px',
			        layout: 'form',
			        frame: false,
			        width: 380,
			        defaultType: 'textfield',
			        border: false,
			        labelWidth: 150,
                    items: [{
				        fieldLabel: 'Inserisci il tuo indirizzo email',
				        name: 'email',
				        width: 200,
				        allowBlank:false
				    }, this.rpMessage = new Ext.Panel({
			            width:370,
			            border: false
			        })]
                })
            }
        });
        

        
        var vp = new Ext.Viewport({
          layout: 'center',
          items:[p = new Ext.Panel({
            border: true,
            width: 772,
            layout: 'border',
            items:[{
                border: false,
                region: 'north',
                height: 187,
                html:'<div style="float:left"><img src="images/logo_sx.jpg"></img></div><div style="float:left"><img src="images/payoff.jpg"></img></div>'
            },this.main = new Ext.Panel({
                border: false,
                region:'center',
                layout: 'card',
                activeItem: logged ? 1 : 0,
                items:[{
				    id: 'login',
				    height: 400,
				    border: false,
				    style: 'text-align:center;',
				    items: this.loginPanel = new Ext.form.FormPanel({
					    layout: 'form',
					    width: 370,
					    title: 'Login',
					    frame:true,
					    style: 'text-align:left;position: relative;margin: 0px auto;padding:5px 5px 5px 5px;',
					    defaultType: 'textfield',
					    labelWidth: 100,
					    items: [{
						        id: 'fldUsername',
							    fieldLabel: 'Username',
							    name: 'username',
							    width: 200,
							    allowBlank:false
						    },{
						        id: 'fldPassword',
							    fieldLabel: 'Password',
							    inputType: 'password',
							    name: 'password',
							    width: 200,
							    allowBlank:false
						    },{
						        id: 'chkRemember',
						        xtype: 'checkbox',
							    fieldLabel: 'Login automatico',
							    name: 'remember',
							    checked: logged,
							    width: 200
						    }, this.loginMessage = new Ext.Panel({
						        width:370
						    })
					    ],
					    bbar: new Ext.Toolbar({
					        buttons:[this.rpButton = new Ext.Button({
						        text: 'Hai dimenticato username e/o password?',
						        style: 'left: 100px;',
						        handler: this.rpWinShow,
						        scope: this
					        }),'->',{
						        text: 'Entra',
						        style: 'left: 100px;',
						        handler: this.login,
						        scope: this
					        }]
					    })
				    })
			    }, {
                    id: 'fatture',
                    xtype:'grid',
                    store: this.store,
                    border: true,
                    frame: true,
                    viewConfig: {
                        getRowClass : function(r) {
                            if(!r.data.downloaded)
                                return 'x-grid3-row-highlight';
                            return '';
                        }
                    },
                    selModel: new Ext.ux.grid.NoSelectionModel({
                    }),
                    columns: [
                        {id:'uid',header: "ID", hidden:true, width: 30, sortable: true, dataIndex: 'uid'},
                        {id:'numero',header: "Numero Fattura", width: 100, align:'center', sortable: true, dataIndex: 'numero'},
                        {id:'data',header: "Data", width: 125, sortable: true, dataIndex: 'data', renderer: function(a){
                            return a.dateFormat('d/m/Y');
                        }},
                        {id:'file',header: "Nome del file", width: 75, sortable: true, dataIndex: 'file'},
                        {id:'download',header: "",sortable:false, width: 30, dataIndex:'file', renderer: function(a,b,c) {
                            return '<img src="images/disk.png" onclick="javascript:app.download(\'' + a + '\', ' + c.data.uid + ');"><img>';
                        }}
                    ],
                    stripeRows: true,
                    autoExpandColumn: 'file',
                    height:400,
                    width:690,
                    frameElement: false,
                    tbar: new Ext.Toolbar({
				        buttons:[{
					        text: 'Aggiorna',
					        handler: this.store.reload,
					        scope: this.store
				        },{
					        text: 'Tutte le fatture',
					        enableToggle: true,
					        allowDepress: true,
					        store: this.store,
					        handler: function() {
					            if(!this.pressed) {
					                this.setText('Tutte le fatture');
					                this.store.baseParams = {todownload:false};
					                this.store.reload();
					            }
					            else {
					                this.setText('Fatture non scaricate');
					                this.store.baseParams = {todownload:true};
					                this.store.reload();
					            }
					        }
				        },'->',{
					        text: 'Cambia password',
//					        style: 'left: 100px;',
					        handler: this.cpWinShow,
					        scope: this
				        },{
					        text: 'Esci',
//					        style: 'left: 100px;',
					        handler: this.logout,
					        scope: this
				        }]
				    })
                }]
            })]
          })]
        });

        p.doLayout();
        this.store.load();
    }
};