﻿Ext.Direct.addProvider(eMessage.PickupHandler);
Ext.Direct.addProvider(eMessage.UserHandler);
Ext.Direct.addProvider(eMessage.CreditHandler);

Ext.onReady(function(){
    var _packages = new Array();
        
    var btnAddPackage = new Ext.Button({
        text: 'Aggiungi pacchetto buste',
        iconCls: 'icon-table-add'
    });
    
    var btnRemovePackage = new Ext.Button({
        text: 'Rimuovi pacchetto buste',
        iconCls: 'icon-table-delete',
        disabled: true
    });
    
    var btnSendPackages = new Ext.Button({
        text: 'Crea bolla di affido',
        disabled: true,
        iconCls: 'icon-table-save'
    });
    
    var storePackages = new Ext.data.DirectStore({
		remoteSort: false,
        autoLoad: false,
        reader: new Ext.data.JsonReader({
	        idProperty: 'id',
	        root: 'data',
	        allowBlank:false,
	        paramsAsHash: true,
		    fields: Ext.data.Record.create([
	            {name: 'id', type: 'int', mapping: 'id'},
		        
		        {name: 'customerCodeText', type: 'string', mapping: 'customerCodeText'},
		        
		        {name: 'stampType', type: 'string', mapping: 'stampType'},
		        {name: 'stampTypeText', type: 'string', mapping: 'stampTypeText'},
		        
		        {name: 'countryType', type: 'string', mapping: 'countryType'},
		        {name: 'countryTypeText', type: 'string', mapping: 'countryTypeText'},
		        
		        {name: 'letterNumber', type: 'int', mapping: 'letterNumber'},
		        
		        {name: 'weightRangeId', type: 'int', mapping: 'weightRangeId'},
		        {name: 'weightRangeText', type: 'string', mapping: 'weightRangeText'},
		        
		        {name: 'servicePrice', type: 'float', mapping: 'servicePrice'},
		        {name: 'servicePriceText', type: 'string', mapping: 'servicePriceText'},
		        
		        {name: 'stampPrice', type: 'float', mapping: 'stampPrice'},
		        {name: 'stampPriceText', type: 'string', mapping: 'stampPriceText'},
		        
		        {name: 'totalPrice', type: 'float', mapping: 'totalPrice'},
		        {name: 'totalPriceText', type: 'string', mapping: 'totalPriceText'}
		        
	        ])
	    })
    });
    
    var _pickupPackage = new storePackages.recordType({
        id : 999,
                
        customerCodeText : '-',
        
        stampType : 'Pickup',
        stampTypeText : 'Onere per ritiro corrispondenza',
        
        letterNumber : 1, 
        
        countryType : '',
        countryTypeText : '',
        
        weightRangeId : 0, 
        weightRangeText : '-',
        
        servicePrice : 9.6,
        servicePriceText : '9.60 &euro;',
        
        stampPrice : 0,
        stampPriceText : '-',
        
        totalPrice : 9.6,
        totalPriceText : '9.60 &euro;'
    });
    
    storePackages.add(_pickupPackage);
    
    var total = 9.6;
    
    var dfTotal = new Ext.form.DisplayField({
        hideLabel: true,
        value: 'Totale: <b>' + euroMoney2(total) + '</b>',
        cls: 'dfTotalClass'
    });

    var bottomToolbar = new Ext.Toolbar({
        items: [ '->', dfTotal ]
    });
    
    var gridPackages = new Ext.grid.GridPanel({
        loadMask: true,
        title: 'Elenco pacchetti',
        height: 350,
        frame: false,
        bodyStyle:'margin-bottom:5px',
        bbar: bottomToolbar,
        columns: [
	        {dataIndex: 'id', id:'id', sortable: false, hidden: true},
	        
	        {dataIndex: 'customerCodeText', header: "Note cliente"},
	        
	        {dataIndex: 'stampType', hidden: true},
	        {dataIndex: 'stampTypeText', header: "Affrancatura e servizi richiesti"},
	        
	        {dataIndex: 'countryType', hidden: true},
	        {dataIndex: 'countryTypeText', header: "Destinazione"},
	        
	        {dataIndex: 'letterNumber', header: "Quantit&agrave;", width: 50},
	        
	        {dataIndex: 'pagesPerLetter', sortable: false, hidden: true},
	        
	        {dataIndex: 'weightRangeId', hidden: true},
	        {dataIndex: 'weightRangeText', header: "Peso per lettera"},
	        
	        {dataIndex: 'servicePrice', hidden: true},
	        {dataIndex: 'servicePriceText', header: "Servizi", renderer: euroMoney2, width: 50},
	        
	        {dataIndex: 'stampPrice', hidden: true},
	        {dataIndex: 'stampPriceText', header: "Bolli", renderer: euroMoney2, width: 50},
	        
	        {dataIndex: 'totalPrice', hidden: true},
	        {dataIndex: 'totalPriceText', header: "Totale", renderer: euroMoney2, width: 50}
	    ],
	    viewConfig: {
            forceFit: true,
            getRowClass: function(rec, rowIdx, params, store) {
				return rec.get('id') == 999 ? 'pickup-row' : '';
			}
        },
        store: storePackages
    });
    
    gridPackages.getSelectionModel().on('selectionchange', function(){
        var rec = gridPackages.getSelectionModel().getSelected();
        if (rec != undefined) {
            var value = rec.get('id');
            if (value != '999' && value != undefined && value != '')
                btnRemovePackage.enable();
            else
                btnRemovePackage.disable();
        }
    }, this, {buffer:10});
    
    var tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate()+1);
    
    var btnSubmit = new Ext.Button({
        text: 'Crea Bolla di Affido',
        iconCls: 'icon-table-save'
    });
    
    var counterId = 0;
   
    function showAddPackageWizard() {
        var stampTypeValue = "";
        var stampTypeDisplay = "";
        var countryTypeValue = "";
        var countryTypeDisplay = "";
        var sheetsPerLetterValue = "";
        var sheetsPerLetterDisplay = "";
        
        var tbCustomerCode = new Ext.form.TextField({
            id: 'tbCustomerCode',
            fieldLabel: 'Note',
            allowBlank: true,
            anchor: '-18',
            bodyStyle  : 'padding-top: 2em;'
        });
        
        var tbLettersQuantity = new Ext.form.TextField({
            id: 'tbLettersQuantity',
            fieldLabel: 'Quantit&agrave; buste',
            allowBlank: false,
            maskRe: /[\d\/]/,
            anchor: '-18'
        });
                
        var cmbSheetsPerLetter = new Ext.form.ComboBox({
            id: 'cmbSheetsPerLetter',
            fieldLabel: 'Fogli per lettera',
            allowBlank: false,
            maskRe: /[\d\/]/,
            editable: false,
            anchor: '-18',
			mode: 'local',
			displayField: 'text',
			valueField: 'id',
			triggerAction: 'all',
			emptyText: 'Scegliere il numero di fogli per lettera',
			store: new Ext.data.SimpleStore({
				fields: ['id', 'text'],
				data : [['1', 'Da 1 a 3 fogli (fino a 20 g.)'], 
						['2', 'Da 4 a 8 fogli (oltre 20 g. e fino a 50 g.)'], 
						['3', 'Da 9 a 17 fogli (oltre 50 g. e fino a 100 g.)'],
						['4', 'Da 18 a 45 fogli (oltre 100 g. e fino a 250 g.)'],
						['5', 'Da 46 a 62 fogli (oltre 250 g. e fino a 350 g.)'],
						['6', 'Da 63 a 185 fogli (oltre 350 g. e fino a 1000 g.)'],
						['7', 'Da 186 a 200 fogli (oltre 1000 g. e fino a 2000 g.)']]
			}),
			listeners: {
        	    select: function(combo, record, index) {
        		    sheetsPerLetterValue = record.get(combo.valueField);
        		    sheetsPerLetterDisplay = record.get(combo.displayField);
        	    }
            }
        });
        
        var cmbStampType = new Ext.form.ComboBox({
            fieldLabel:'Affrancatura',
            mode: 'local',
            displayField: 'text',
            valueField: 'id',
            editable: false,
            triggerAction: 'all',
            anchor: '-18',
            maskRe: /[\d\/]/,
            emptyText: 'Scegliere il tipo di affrancatura',
            allowBlank: false,
            store: new Ext.data.SimpleStore({
                fields: ['id', 'text'],
                data : [['PRIORITARIA', 'Posta prioritaria'], 
                        ['RACCOMANDATA', 'Raccomandata'], 
                        ['RACCOMANDATAAR', 'Raccomandata A.R. (cartolina di ritorno da stampare)'],
                        ['RACCOMANDATAAR_CONCARTOLINA', 'Raccomandata A.R. (cartolina di ritorno già stampata)']]
            }),
            listeners: {
        	    select: function(combo, record, index) {
        		    stampTypeValue = record.get(combo.valueField);
        		    stampTypeDisplay = record.get(combo.displayField);
        	    }
            }
        });
        
        var cmbCountryType = new Ext.form.ComboBox({
            fieldLabel:'<a href="http://poste.it/postali/raccomandata/zone.shtml" target="_blank">Destinazione</a>',
            mode: 'local',
            displayField: 'text',
            valueField: 'id',
            editable: false,
            triggerAction: 'all',
            anchor: '-18',
            maskRe: /[\d\/]/,
            emptyText: 'Scegliere la località di destinazione',
            allowBlank: false,
            store: new Ext.data.SimpleStore({
                fields: ['id', 'text'],
                data : [['', 'Italia'], 
                        ['_Estero_Zona1', 'Estero (Zona 1)'], 
                        ['_Estero_Zona2', 'Estero (Zona 2)'],
                        ['_Estero_Zona3', 'Estero (Zona 3)']]
            }),
            listeners: {
        	    select: function(combo, record, index) {
        		    countryTypeValue = record.get(combo.valueField);
        		    countryTypeDisplay = record.get(combo.displayField);
        	    }
            }
        });
        
        var cardLetterNumber = new Ext.ux.Wiz.Card({
    	    id: 'cardLetterNumber',
            title: 'Caratteristiche pacchetto',
            monitorValid : true,
            items: [ 
                tbLettersQuantity,
                cmbSheetsPerLetter,
                cmbStampType,
                cmbCountryType,
                tbCustomerCode
            ]
        });

        var counterId = 0;
	    var letterWizard1 = new Ext.ux.Wiz({
            title : 'Spedizione di lettere con stampa in proprio: procedura guidata',
            previousButtonText : 'Indietro',
            nextButtonText : 'Avanti',
            finishButtonText : 'Fine',
            cancelButtonText : 'Annulla',
            height: 450,
            width: 650,
            modal: true,

            headerConfig : {
                title : '',
                stepText : "Fase {0} di {1}: {2}"
            },
            
            cardPanelConfig : {
                defaults : {
                    baseCls    : 'x-small-editor',
                    bodyStyle  : 'padding:20px 15px 0px 120px;background-color:#F6F6F6;'+
                			     'background-image:url(\'\/Resources\/Images\/Icons\/package.png\');'+
                			     'background-repeat: no-repeat;'+
                			     'background-position: left bottom;',
                    border     : false
                }
            },
            
            cards : [
        	    // CARD: Benvenuti
                new Ext.ux.Wiz.Card({
            	    id	: 'cardWelcome',
                    title : 'Benvenuti',
                    monitorValid : true,
                    items : [{
                            border    : false,
                            bodyStyle : 'background:none;',
                            html      : 'Benvenuti nella procedura guidata per la <b>spedizione di lettere con stampa in proprio</b> '  
                        }]
                }),
                cardLetterNumber
            ],
            listeners:{
        	    finish: {
        		    fn:function() {
        				
        		        var msgMask = Ext.MessageBox.wait('Creazione pacchetto in corso...');
        		        
        		        var lettersQuantity = this.getWizardData().cardLetterNumber.tbLettersQuantity;
        		        var customerCode = this.getWizardData().cardLetterNumber.tbCustomerCode;
        		        counterId++;
        		        
        		        eMessage.Pickup.CalculateSpeditionPrice(
        		            parseInt(lettersQuantity),
        		            parseInt(sheetsPerLetterValue),
        		            stampTypeValue + countryTypeValue,
        		            function(response, e){
        						
        		                var speditionPrice = 
        							parseFloat(response.TotalServicePrice) + parseFloat(response.TotalStampPrice);
        							
        					    total += speditionPrice;
        					    dfTotal.setValue('Totale: <b>' + euroMoney2(total) + '</b>');
        							
        						var speditionServicePrice =  parseFloat(response.TotalServicePrice);		
        						var speditionStampPrice = parseFloat(response.TotalStampPrice);
        		                                		                        
                                var _packages = storePackages.recordType;
                                var _package = new _packages({
                                    id : counterId,
                                    
                                    customerCodeText : customerCode,
                                    
                                    stampType : stampTypeValue,
                                    stampTypeText : stampTypeDisplay,
                                    
                                    countryType : countryTypeValue,
                                    countryTypeText : countryTypeDisplay,
                                    
                                    letterNumber : parseInt(lettersQuantity), 
                                                                
                                    weightRangeId : sheetsPerLetterValue,
                                    weightRangeText : sheetsPerLetterDisplay, 
                                    
                                    servicePrice : parseFloat(speditionServicePrice),
                                    servicePriceText : speditionServicePrice,
                                    
                                    stampPrice : parseFloat(speditionStampPrice),
                                    stampPriceText : speditionStampPrice,
                                    
                                    totalPrice : parseFloat(speditionPrice),
                                    totalPriceText : speditionPrice
                                });
                                
                                storePackages.add(_package);
                                btnSendPackages.enable();
                                
                                Ext.MessageBox.hide();
                            }
                        );
        		    }
        		}
            }
        });

        letterWizard1.show();
    }
        
    var formPickup = new Ext.FormPanel({
        bodyStyle:'padding:15px 5px 0',
        width: 830,
        border: false,
        //iconCls: 'icon-table-edit',
        buttonAlign: 'center',
        //title: 'Bolla di Affido',
        items: [gridPackages],
        tbar: [
            btnAddPackage,
            btnRemovePackage,
            btnSendPackages
        ],
        renderTo: Ext.get('divPickupForm')
    });
    
    var deliveryDate;
    
    function showCreatePackageWizard() {
        
        var dfDeliveryDate = new Ext.form.DisplayField({
            id: 'dfDeliveryDate',
            hideLabel: true
            //fieldLabel: 'Data ritiro prevista'
        });
        
        // CARD: Mittente
        var cardSender = new Ext.ux.Wiz.Card({
    	    id	: 'cardSender',
            title : 'Mittente',
            monitorValid : true,
            items : [{
                    border    : false,
                    bodyStyle : 'background:none;',
                    html      : 'Indicare i dati relativi al <b>mittente</b>.<br/>&nbsp;' ,
                },
	            new Ext.form.TextField({
		            id: 'tbNome',
		            anchor: '-18',
		            fieldLabel: 'Nome',
		            allowBlank: true
	            }),
	            new Ext.form.TextField({
		            id: 'tbCognome',
	                anchor: '-18',
	                fieldLabel: 'Cognome',
		            allowBlank: true
	            }),
	            new Ext.form.TextField({
		            id: 'tbAzienda',
	                anchor: '-18',
	                fieldLabel: 'Azienda',
		            allowBlank: true
	            }),
	            new Ext.form.TextField({
		            id: 'tbIndirizzo',
	                anchor: '-18',
	                fieldLabel: 'Indirizzo',
	                allowBlank : false
	            }),
	            new Ext.form.TextField({
		            id: 'tbCap',
	                anchor: '-18',
	                fieldLabel: 'CAP',
	                maskRe: /[\d\/]/,
	                allowBlank : false
	            }),
	            new Ext.form.TextField({
		            id: 'tbComune',
	                anchor: '-18',
	                fieldLabel: 'Comune',
	                allowBlank : false
	            }),
	            new Ext.form.TextField({
		            id: 'tbProvincia',
	                anchor: '-18',
	                fieldLabel: 'Provincia',
	                allowBlank : false
	            }),
	            {
                    border    : false,
                    bodyStyle :'padding:15px 0px 0px 0px; background:none;',
                    html      : 'Un addetto SPI (Servizi Postali Italiani) o un corriere SDA si occuperanno del ritiro del materiale.' 
                },
                dfDeliveryDate
            ],
            nextCardFn: function(panel){               
		        if (Ext.get('SignupDisabled').dom.innerHTML == 'true')
		            return 3;
		        else
		            return 2;
	        },
	        listeners: {
        	    beforecardhide: function() {
        	        if (pickupWizard.lastAction == 'next') {       	            
        	            cookieProvider.clear('tbNome');
        	            cookieProvider.clear('tbCognome');
        	            cookieProvider.clear('tbAzienda');
        	            cookieProvider.clear('tbIndirizzo');
        	            cookieProvider.clear('tbCap');
        	            cookieProvider.clear('tbComune');
        	            cookieProvider.clear('tbProvincia');
        	            
        	            cookieProvider.set('tbNome', Ext.getCmp('tbNome').getValue());
        	            cookieProvider.set('tbCognome', Ext.getCmp('tbCognome').getValue());
        	            cookieProvider.set('tbAzienda', Ext.getCmp('tbAzienda').getValue());
        	            cookieProvider.set('tbIndirizzo', Ext.getCmp('tbIndirizzo').getValue());
        	            cookieProvider.set('tbCap', Ext.getCmp('tbCap').getValue());
        	            cookieProvider.set('tbComune', Ext.getCmp('tbComune').getValue());
        	            cookieProvider.set('tbProvincia', Ext.getCmp('tbProvincia').getValue());
        	        }
        	    }
            }
        });
        
        var cardFinishText = new Ext.form.DisplayField({
            id: 'dfFinish',
            hideLabel: true,
            allowBlank : false,
            value: ''
        });
        
        var cardFinish = new Ext.ux.Wiz.Card({
    	    id: 'cardFinish',
            title: 'Riepilogo',
            monitorValid: true,
            items: [
                cardFinishText
            ],
            isFinish: true,
            //prevCard: 2,
            prevCardFn: function(panel){               
		        if (Ext.get('SignupDisabled').dom.innerHTML == 'true')
		            return 1;
		        else
		            return 2;
	        },
        });

        var cardLogin = new Ext.ux.Wiz.Card({
    	    id	: 'cardLogin',
            title : 'Login',
            monitorValid : true,
            items: [
                new Ext.form.TextField({
		            id: 'tbLoginUsername',
	                anchor: '-18',
	                fieldLabel: 'Username',
	                allowBlank : false
	            }),
	            new Ext.form.TextField({
		            id: 'tbLoginPassword',
	                anchor: '-18',
	                fieldLabel: 'Password',
	                allowBlank : false,
	                inputType: 'password'
	            })
            ],
            //prevCard: 2,
            prevCardFn: function(panel){               
		        if (Ext.get('SignupDisabled').dom.innerHTML == 'true')
		            return 1;
		        else
		            return 2;
	        },
            nextCard: 5,
            listeners: {
        	    beforecardhide: function() {
        	        if (pickupWizard.lastAction == 'next') {
        	            Ext.MessageBox.wait('Login in corso...');
        	            
        	            cookieProvider.clear('tbLoginUsername');
        	            cookieProvider.set('tbLoginUsername', Ext.getCmp('tbLoginUsername').getValue());
            	        
        	            eMessage.User.Login(
    		                Ext.getCmp('tbLoginUsername').getValue(),
    		                Ext.getCmp('tbLoginPassword').getValue(),
    		                function(response, e){
    		                    
    		                    if (response.success) {
    		                        Ext.MessageBox.wait('Controllo del credito residuo...');
    		                        
    		                        eMessage.Credit.HasCreditForPickupSpedition(
    		                            Ext.getCmp('tbLoginUsername').getValue(),
    		                            Ext.getCmp('tbLoginPassword').getValue(),
    		                            parseFloat(total),
    		                            function(response, e){
    		                                Ext.MessageBox.hide();
    		                                if (response.hasCredit)
    		                                    pickupWizard.cardPanel.getLayout().setActiveItem(6);
    		                                else
    		                                {
    		                                    cardFinishText.setValue(
        	                                        '<p>La bolla di affido è pronta per essere creata.</p>' +
                                                    '<p>Il costo totale della spedizione è di <b>' + euroMoney2(total) + '</b></p>' + 
                                                    '<p>Premendo il pulsante <i>Fine</i> sarà trasferito alla pagina di pagamento sicuro di <b>Paypal</b>. Al termine del pagamento riceverà una email contenente la bolla di affido che dovrà stampare, firmare e consegnare al corriere che si occuperà del ritiro della sua posta.' +
                                                    '<p><b>Alla transazione sarà applicata una maggiorazione del 4% come rivalsa spese per gestione incassi con carta di credito.</b></p>');  
    		                                    pickupWizard.cardPanel.getLayout().setActiveItem(7);
    		                                }
    		                            }
    		                        );
    		                    }
    		                    else {
    		                        pickupWizard.cardPanel.getLayout().setActiveItem(3);
        		                    
    		                        Ext.MessageBox.show({
                                        title: 'Errore',
                                        msg: response.error,
                                        buttons: Ext.MessageBox.OK,
                                        animEl: 'mb9',
                                        icon: 'ext-mb-error'
                                    });
    		                    }
    	                    }
        	            );
                    }
                    
        	        return true;
        	    }
            }
        });
        
        var cardSignup = new Ext.ux.Wiz.Card({
    	    id	: 'cardSignup',
            title : 'Registrazione ai servizi ' + softwareName,
            monitorValid : true,
            items: [
                new Ext.form.TextField({
		            id: 'tbSignupUsername',
	                anchor: '-18',
	                fieldLabel: 'Username (Email)',
	                allowBlank : false
	            }),
	            new Ext.form.TextField({
		            id: 'tbSignupPassword',
	                anchor: '-18',
	                fieldLabel: 'Password',
	                allowBlank : false,
	                inputType: 'password'
	            }),
	            new Ext.form.TextField({
		            id: 'tbSignupFirstName',
	                anchor: '-18',
	                fieldLabel: 'Nome',
	                allowBlank : false
	            }),
	            new Ext.form.TextField({
		            id: 'tbSignupLastName',
	                anchor: '-18',
	                fieldLabel: 'Cognome',
	                allowBlank : false
	            }),
	            new Ext.form.TextField({
		            id: 'tbSignupCompany',
	                anchor: '-18',
	                fieldLabel: 'Azienda',
	                allowBlank : false
	            }),
	            new Ext.form.TextField({
		            id: 'tbSignupAddress',
	                anchor: '-18',
	                fieldLabel: 'Indirizzo',
	                allowBlank : false
	            }),
	            new Ext.form.TextField({
		            id: 'tbSignupZip',
	                anchor: '-18',
	                fieldLabel: 'CAP',
	                allowBlank : false
	            }),
	            new Ext.form.TextField({
		            id: 'tbSignupCity',
	                anchor: '-18',
	                fieldLabel: 'Comune',
	                allowBlank : false
	            }),
	            new Ext.form.TextField({
		            id: 'tbSignupProvince',
	                anchor: '-18',
	                fieldLabel: 'Provincia',
	                allowBlank : false
	            }),
	            new Ext.form.TextField({
		            id: 'tbSignupTaxCode',
	                anchor: '-18',
	                fieldLabel: 'Codice Fiscale',
	                allowBlank : true
	            }),
	            new Ext.form.TextField({
		            id: 'tbSignupVatNumber',
	                anchor: '-18',
	                fieldLabel: 'Partita IVA',
	                allowBlank : true
	            }),
	            new Ext.form.TextField({
		            id: 'tbSignupMobileNumber',
	                anchor: '-18',
	                fieldLabel: 'Numero cellulare',
	                allowBlank : false
	            })
            ],
            nextCard: 5,
            prevCard: 2,
            listeners: {
        	    beforecardhide: function() {
        	    
        	        if (pickupWizard.lastAction == 'next') {
        	            Ext.MessageBox.wait('Iscrizione in corso...');
            	        
        	            eMessage.User.SignUp(
    		                Ext.getCmp('tbSignupUsername').getValue(),
    		                Ext.getCmp('tbSignupPassword').getValue(),
    		                Ext.getCmp('tbSignupFirstName').getValue(),
    		                Ext.getCmp('tbSignupLastName').getValue(),
    		                Ext.getCmp('tbSignupCompany').getValue(),
    		                Ext.getCmp('tbSignupAddress').getValue(),
    		                Ext.getCmp('tbSignupCity').getValue(),
    		                Ext.getCmp('tbSignupZip').getValue(),
    		                Ext.getCmp('tbSignupProvince').getValue(),
    		                Ext.getCmp('tbSignupTaxCode').getValue(),
    		                Ext.getCmp('tbSignupVatNumber').getValue(),
    		                Ext.getCmp('tbSignupMobileNumber').getValue(),
    		                function(response, e){
    		                    Ext.MessageBox.hide();
    		                    if (response.success) {
    		                        pickupWizard.cardPanel.getLayout().setActiveItem(6);
    		                    }
    		                    else {
    		                        pickupWizard.cardPanel.getLayout().setActiveItem(4);
        		                    
    		                        Ext.MessageBox.show({
                                        title: 'Errore',
                                        msg: response.error,
                                        buttons: Ext.MessageBox.OK,
                                        animEl: 'mb9',
                                        icon: 'ext-mb-error'
                                    });
    		                    }
    	                    }
        	            );
                    }
        	        return true;
        	    }
            }
        });
        
        var eMessageExistingAccount = new Ext.form.Radio({
            name:'eMessageNewAccount',
            boxLabel: 'Sono già iscritto a ' + softwareName,
            inputValue: 'no',
            checked: true,
            hideLabel: true
        });
        
        var eMessageNewAccount = new Ext.form.Radio({
            name:'eMessageNewAccount',
            boxLabel: 'Non sono iscritto a ' + softwareName,
            inputValue: 'yes',
            hideLabel: true
        })
        
        // CARD: Mittente
        var cardAccount = new Ext.ux.Wiz.Card({
    	    id	: 'cardAccount',
            title : 'Mittente',
            monitorValid : true,
            items : [
                eMessageExistingAccount,
                eMessageNewAccount
            ],
            nextCardFn: function(panel){
		        if (pickupWizard.getWizardData().cardAccount.eMessageNewAccount == 'no')
		            return 3;
		        else {
		            cardFinishText.setValue(
        	                '<p>La bolla di affido è pronta per essere creata.</p>' +
                            '<p>Il costo totale della spedizione è di <b>' + euroMoney2(total) + '</b></p>' + 
                            '<p>Premendo il pulsante <i>Fine</i> sarà trasferito alla pagina di pagamento sicuro di <b>Paypal</b>. Al termine del pagamento riceverà una email contenente la bolla di affido che dovrà stampare, firmare e consegnare al corriere che si occuperà del ritiro della sua posta.');  
                            
		            return 4;
		        }
	        }
        });
        
        var amountFromCreditCard = new Ext.form.Radio({
            name:'amountFromExistingCredit',
            boxLabel: 'Utilizza la carta di credito per pagare questa spedizione',
            inputValue: 'no',
            checked: true,
            hideLabel: true
        });
        
        var amountFromExistingCredit = new Ext.form.Radio({
            name:'amountFromExistingCredit',
            boxLabel: 'Utilizza il credito esistente',
            inputValue: 'yes',
            hideLabel: true
        })
        
        // CARD: Mittente
        var cardPaymentType = new Ext.ux.Wiz.Card({
    	    id	: 'cardPaymentType',
            title : 'Tipo di pagamento',
            monitorValid : true,
            items : [
                amountFromCreditCard,
                amountFromExistingCredit
            ],
            listeners: {
        	    beforecardhide: function() {
        	        if (pickupWizard.getWizardData().cardPaymentType.amountFromExistingCredit == 'yes')
		                cardFinishText.setValue(
        	                '<p>La bolla di affido è pronta per essere creata.</p>' +
                            '<p>Il costo totale della spedizione è di <b>' + euroMoney2(total) + '</b></p>' + 
                            '<p>Premendo il pulsante <i>Fine</i> riceverà una email contenente la bolla di affido che dovrà stampare, firmare e consegnare al corriere che si occuperà del ritiro della sua posta.');
		            else
		                cardFinishText.setValue(
        	                '<p>La bolla di affido è pronta per essere creata.</p>' +
                            '<p>Il costo totale della spedizione è di <b>' + euroMoney2(total) + '</b></p>' + 
                            '<p>Premendo il pulsante <i>Fine</i> sarà trasferito alla pagina di pagamento sicuro di <b>Paypal</b>. Al termine del pagamento riceverà una email contenente la bolla di affido che dovrà stampare, firmare e consegnare al corriere che si occuperà del ritiro della sua posta.' +
                            '<p><b>Alla transazione sarà applicata una maggiorazione del 4% come rivalsa spese per gestione incassi con carta di credito.</b></p>');    
        	    }
        	},
        	prevCard: 3
        });

        var pickupWizard = new Ext.ux.Wiz({
            title : 'Creazione bolla di affido: procedura guidata',
            previousButtonText : 'Indietro',
            nextButtonText : 'Avanti',
            finishButtonText : 'Fine',
            cancelButtonText : 'Annulla',
            height: 450,
            modal: true,
            closable: false,

            headerConfig : {
                title : '',
                stepText : "Fase {0} di {1}: {2}"
            },
            
            cardPanelConfig : {
                defaults : {
                    baseCls    : 'x-small-editor',
                    bodyStyle  : 'padding:20px 15px 0px 120px;background-color:#F6F6F6;'+
                			     'background-image:url(\'\/Resources\/Images\/Icons\/Mail.png\');'+
                			     'background-repeat: no-repeat;'+
                			     'background-position: left bottom;',
                    border     : false
                }
            },
            
            cards : [
        	    // CARD: Benvenuti
                new Ext.ux.Wiz.Card({
            	    id	: 'cardWelcome',
                    title : 'Benvenuti',
                    monitorValid : true,
                    items : [{
                            border    : false,
                            bodyStyle : 'background:none;',
                            html      : 'Benvenuti nella procedura guidata per la <b>creazione della bolla di affido</b> '  
                        }]
                }),
                cardSender,
                cardAccount,
                cardLogin,
                cardSignup,
                new Ext.ux.Wiz.Card({
            	    id	: 'cardWait',
                    title : 'Attendere',
                    monitorValid : true,
                    items : [{
                            border    : false,
                            bodyStyle : 'background:none;',
                            html      : ''  
                    }],
                    prevCard: 2
                }),
                cardPaymentType,
                cardFinish
            ],
            listeners:{
        	    finish: {
        		    fn:function() {
        				
        		        Ext.MessageBox.wait('Elaborazione bolla di affido in corso...');
        		        
        		        var _packages = new Array(storePackages.data.length);
                        for (var i=0; i < storePackages.data.length; i++)
                        {
                            _packages[i] = new Object();
                            
                            _packages[i]['customerCodeText'] = storePackages.data.items[i].data.customerCodeText;
                            _packages[i]['SpeditionType'] = storePackages.data.items[i].data.stampType;
                            _packages[i]['CountryType'] = storePackages.data.items[i].data.countryTypeText;
                            _packages[i]['LetterNumber'] = storePackages.data.items[i].data.letterNumber;
                            _packages[i]['WeightRange'] = storePackages.data.items[i].data.weightRangeId;
                            _packages[i]['TotalCost'] = storePackages.data.items[i].data.totalPrice;
                            _packages[i]['ServiceCost'] = storePackages.data.items[i].data.servicePrice;
                            _packages[i]['StampCost'] = storePackages.data.items[i].data.stampPrice;
                        }
                        
                        var myDate=new Date();
                        
                        var _username = '';
                        var _password = '';
                        
                        if (pickupWizard.getWizardData().cardAccount.eMessageNewAccount == 'yes') {
                            _username = this.getWizardData().cardSignup.tbSignupUsername;
                            _password = this.getWizardData().cardSignup.tbSignupPassword;
                        }
                        else {
                            _username = this.getWizardData().cardLogin.tbLoginUsername;
                            _password = this.getWizardData().cardLogin.tbLoginPassword;
                        }
                        
                        eMessage.Pickup.InsertPickupTempData(
                            _username,
                            _password,
                            _packages,
                            this.getWizardData().cardSender.tbNome,
                            this.getWizardData().cardSender.tbCognome,
                            this.getWizardData().cardSender.tbAzienda,
                            this.getWizardData().cardSender.tbIndirizzo,
                            this.getWizardData().cardSender.tbComune,
                            this.getWizardData().cardSender.tbProvincia,
                            this.getWizardData().cardSender.tbCap,
                            this.getWizardData().cardSender.dfDeliveryDate,
                            function(response, e) {
                                if (response.success) {  
                                    if (pickupWizard.getWizardData().cardPaymentType.amountFromExistingCredit == 'yes') {
		                                eMessage.Pickup.CreatePickup(
		                                    _username,
		                                    _password,
		                                    response.description,
		                                    function(response, e) {
		                                        if (response.success) {
		                                            location.href = '/Pickup-Return-Ok.aspx';
		                                        }
		                                        else {
		                                            Ext.MessageBox.show({
                                                        title: 'Errore',
                                                        msg: response.error,
                                                        buttons: Ext.MessageBox.OK,
                                                        animEl: 'mb9',
                                                        icon: 'ext-mb-error'
                                                    });
		                                        }
		                                    });
		                            }
		                            else {
		                                Ext.MessageBox.wait('Connessione al sito sicuro di Paypal in corso...');
		                                document.getElementById('amount_1').value = euroRound(total/1.2);
		                                document.getElementById('amount_2').value = euroRound(total*0.04);
                                        document.getElementById('tax_1').value = euroRound(total-(total/1.2));
                                        document.getElementById('custom').value = response.description;
                                        document.getElementById('formPayPal').submit();
		                            }
                                }
                                else {
                                    Ext.MessageBox.show({
                                        title: 'Errore',
                                        msg: response.error,
                                        buttons: Ext.MessageBox.OK,
                                        animEl: 'mb9',
                                        icon: 'ext-mb-error'
                                    });
                                }
                            }
                        );
        		    }
        		},
        		cancel: {
        		    fn:function() {
        		        btnAddPackage.enable();
                        btnSendPackages.enable();
                        
                        pickupWizard.closable = true;
                        pickupWizard.close();
                    }
        		}
            }
        });
        
        eMessage.Pickup.GetPickupDateTime(function(response, e) {
		    Ext.getCmp('dfDeliveryDate').setValue(
		        '<br /><b>Data ritiro prevista: <u>' + dateFormat(response.description, 'dddd d mmmm yyyy')) + '</u></b>';
    		    
		    deliveryDate = response.description;
        });
        
        if (cookieProvider.get('tbLoginUsername', '') != '')
            Ext.getCmp('tbLoginUsername').setValue(cookieProvider.get('tbLoginUsername', ''));
        
        Ext.getCmp('tbNome').setValue(cookieProvider.get('tbNome', ''));
        Ext.getCmp('tbCognome').setValue(cookieProvider.get('tbCognome', ''));
        Ext.getCmp('tbAzienda').setValue(cookieProvider.get('tbAzienda', ''));
        if (cookieProvider.get('tbIndirizzo', '') != '')
            Ext.getCmp('tbIndirizzo').setValue(cookieProvider.get('tbIndirizzo', ''));
        if (cookieProvider.get('tbCap', '') != '')
            Ext.getCmp('tbCap').setValue(cookieProvider.get('tbCap', ''));
        if (cookieProvider.get('tbComune', '') != '')
            Ext.getCmp('tbComune').setValue(cookieProvider.get('tbComune', ''));
        if (cookieProvider.get('tbProvincia', '') != '')
            Ext.getCmp('tbProvincia').setValue(cookieProvider.get('tbProvincia', ''));
        
        pickupWizard.show();
    }

    btnAddPackage.on('click', function(){
        showAddPackageWizard();
    });
    
    function removePackageWizard(btn) {
        if (btn == 'yes') {
            var rec = gridPackages.getSelectionModel().getSelected();
            var value = rec.get('id');
            
            var speditionPrice = parseFloat(rec.get('totalPrice'));
            
        	total -= speditionPrice;
        	dfTotal.setValue('Totale: <b>' + euroMoney2(total) + '</b>');
        	
        	if (total < 9.61)
   		       btnSendPackages.disable();
               		                        
            storePackages.remove(rec);
        }
    }
    
    btnRemovePackage.on('click', function(){
        Ext.MessageBox.confirm('Conferma eliminazione pacchetto', 
            'Sei sicuro di voler cancellare questo pacchetto?', removePackageWizard);
    });
    
    btnSendPackages.on('click', function(){
        btnAddPackage.disable();
        btnSendPackages.disable();
               
        //winSender.show();
        showCreatePackageWizard();
    });   
});
