// Aggiunta della proprieta' draggable al column model dei grid panels
Ext.override(Ext.grid.HeaderDragZone, {
    getDragData : function(e){
        var t = Ext.lib.Event.getTarget(e);
        var h = this.view.findHeaderCell(t);
        if (h && (this.grid.colModel.config[this.view.getCellIndex(h)].draggable !== false)){
            return {ddel: h.firstChild, header:h};
        }
        return false;
    }	
});

// Combo renderer per le editor grid
Ext.util.Format.ComboRenderer = function(combo){
	return function(value,metadata,record){
        var comboRecord = combo.findRecord(combo.valueField, value);
        return comboRecord ? comboRecord.get(combo.displayField) : value;
    }
}

// Grid fake editor
Ext.namespace("Ext.MedicalSystems","Ext.MedicalSystems.data");
Ext.MedicalSystems.data.FakeEditor = {
	on:function(){},
	render:function(){},
	stopEdit:function(){},
	startEdit:function(){},
	cancelEdit:function(){},
	completeEdit:function(){}
};

// CheckColumn
Ext.grid.CheckColumn = function(config){
	Ext.apply(this, config);
	if(!this.id){
		this.id = Ext.id();
	}
	this.renderer = this.renderer.createDelegate(this);
};
 
Ext.grid.CheckColumn.prototype ={
	init : function(grid){
		this.grid = grid;
		this.grid.on('render', function(){
			var oView = this.grid.getView();
			oView.mainBody.on('mousedown', this.onMouseDown, this);
			oView.mainBody.on('mouseup', this.onClick, this);
		}, this);
	},			
	onClick : function(e, t){
		if(t.className && t.className.indexOf('x-grid3-cc-'+this.id) != -1){
			e.stopEvent();
			var index = this.grid.getView().findRowIndex(t);
			var record = this.grid.store.getAt(index);
			this.click(this, record,index);
		}
	},
	click: Ext.emptyFn,
	onMouseDown : function(e, t){
		if(t.className && t.className.indexOf('x-grid3-cc-'+this.id) != -1){
			e.stopEvent();
			var index = this.grid.getView().findRowIndex(t);
			var record = this.grid.store.getAt(index);
			record.set(this.dataIndex, !record.data[this.dataIndex]);
			record.commit();
		}
	},
	renderer : function(v, p, record){
		if(v == null){
			v = false;
		}
		p.css += ' x-grid3-check-col-td'; 
		return '<div class="x-grid3-check-col'+(v?'-on':'')+' x-grid3-cc-'+this.id+'">&#160;</div>';
	}
};

// Fix del bug della funzione setValue() nelle checkbox 
Ext.form.Checkbox.override({
    setValue : function(v) {
        var checked = this.checked;
        this.checked = (v === true || v === 'true' || v == '1' || String(v).toLowerCase() == 'on');
        
        if(this.rendered){
            this.el.dom.checked = this.checked;
            this.el.dom.defaultChecked = this.checked;
            this.wrap[this.checked? 'addClass' : 'removeClass'](this.checkedCls);
        }
        
        if(checked != this.checked){
            this.fireEvent("check", this, this.checked);
            if(this.handler){
                this.handler.call(this.scope || this, this, this.checked);
            }
        }
    },

    afterRender : function(){
        Ext.form.Checkbox.superclass.afterRender.call(this);
        this.wrap[this.checked? 'addClass' : 'removeClass'](this.checkedCls);
    }
});

// Daterange && Password Matching
Ext.apply(Ext.form.VTypes, {
    daterange : function(val, field) {
        var date = field.parseDate(val);

        if(!date){
            return;
        }
        if (field.startDateField && (!this.dateRangeMax || (date.getTime() != this.dateRangeMax.getTime()))) {
            var start = Ext.getCmp(field.startDateField);
            start.setMaxValue(date);
            this.dateRangeMax = date;
        } 
        else if (field.endDateField && (!this.dateRangeMin || (date.getTime() != this.dateRangeMin.getTime()))) {
            var end = Ext.getCmp(field.endDateField);
            end.setMinValue(date);
            this.dateRangeMin = date;
        }
        
        /* Always return true since we're only using this vtype to set the
         * min/max allowed values (these are tested for after the vtype test)
         */
        return true;
    },

    password : function(val, field) {
        if (field.initialPassField) {
            var pwd = Ext.getCmp(field.initialPassField);
            return (val == pwd.getValue());
        }
        return true;
    },

    passwordText : 'Passwords do not match'
});

function Registration(){
	this.fields = {};
	this.sFinalMsg = 
		
		"La sua richiesta di iscrizione &egrave; stata inviata.<br/><br/>" +
		"Non appena l'attivazione verr&agrave; effettuata ricever&agrave un'email<br/>" +
		"di conferma."
	;
	
	/* INIT */
	this.init = function(){
		var oObj = this;
		
		// CREAZIONE DEI FIELDS
		this.buildFields();
		
		// GRID PANELS PER L'ISCRIZIONE VEQ
		this.oReg_ProfilesGrid = this.buildProfileGrid();
		this.oReg_AnalytesGrid = this.buildAnalytesGrid();
		
		// FORM PRINCIPALE
		var oForm = this.buildForm();
		
		// VIEWPORT
		var oViewPort = new Ext.Viewport({
			layout			: "border",
			bodyStyle		: 'background-color: #FFF;',
			items			: [
				new Ext.Panel({
					title			: 'Pagina di iscrizione al programma VEQ e/o CQI - <a href="./login.php">Online DicoCARE</a> ',
					layout			: 'border',
					bodyStyle		: 'background-color: #FFF;',
					region			: "center",
					autoScroll		: true,
					items			:[oForm]
				})
			]
		});
	}

	/* CREAZIONE DEL FORM DI REGISTRAZIONE */
	this.buildForm = function(){
		var oObj = this;
		
		// FIELDSET PER I DATI DI ACCESSO AL SITO
		var oLoginFieldset = new Ext.form.FieldSet({
			title			: 'Dati di accesso al sito',
			layout			: 'tableform',
			labelWidth		: 160,
			style			:'margin-left:5px;',
			autoWidth		: 200,
			labelSeparator	: ':',
			labelAlign		: 'right',
            defaultType		: 'textfield',
			layoutConfig	: {columns : 1},
			items			: [
				oObj.fields.oSite_Login,
				oObj.fields.oSite_Password,
				oObj.fields.oSite_Password2
			]
		});
		
		// FIELDSET PER L'ANAGRAFICA DEL LABORATORIO
		var oAnagraphicFieldSet = new Ext.form.FieldSet({
			title			: 'Dati anagrafici del laboratorio',
			layout			: 'tableform',
			labelWidth		: 160,
			colspan			: 2,
			style			:'margin-right:10px;',
			autoHeight		: true,
			autoWidth		: true,
			labelSeparator	: ':',
			labelAlign		: 'right',
                        defaultType		: 'textfield',
			layoutConfig	: {columns : 2},
			items			: [
				oObj.fields.oAn_Name,
				oObj.fields.oAn_ReferencePerson,
				oObj.fields.oAn_Address,
				oObj.fields.oAn_City,
				oObj.fields.oAn_Province,
				oObj.fields.oAn_CAP,
				oObj.fields.oAn_Phone,
				oObj.fields.oAn_Mail,
				oObj.fields.oAn_OfficialName,
				oObj.fields.oAn_Type
			],
			listeners : {
				afterlayout : function(oFieldSet){
					oLoginFieldset.setHeight(oFieldSet.getSize().height + 1);
					oLoginFieldset.doLayout();
				}
			}
		});
		
		// FIELDSET PER L'ISCRIZIONE VEQ
		var oRegFieldset = new Ext.form.FieldSet({
			title			: 'Richieste di iscrizione ai programmi',
			layout			: 'tableform',
			colspan			: 3,
			labelWidth		: 160,
			autoHeight		: true,
			autoWidth		: true,
			labelSeparator	: ':',
			labelAlign		: 'right',
                        defaultType		: 'textfield',
			layoutConfig	: {columns : 4},
			items			: [
				oObj.fields.oReg_IsOurCustomer,
				oObj.fields.oReg_CustomerCode,
				oObj.fields.oReg_CQICheckBox,
				oObj.fields.oReg_VEQCheckBox,
				oObj.oReg_ProfilesGrid,
				oObj.oReg_AnalytesGrid
			]
		});
		
		// FIELDSET PER IL DISCLAIMER E PER LA SUA ACCETTAZIONE
		var oDisclaimerFieldset = new Ext.form.FieldSet({
			title			: 'Disclaimer',
			layout			: 'tableform',
			colspan			: 3,
			labelWidth		: 160,
			autoHeight		: true,
			autoWidth		: true,
			labelSeparator	: ':',
			labelAlign		: 'right',
                        defaultType		: 'textfield',
			layoutConfig	: {columns : 1},
			items			: [
				new Ext.Panel({
		        	region			:"center",
				    autoScroll		: true,
				    cls				: 'disclaimer', 
				    border			: false,
					monitorResize 	: true,
					autoLoad		: 'disclaimer.php?no_session'
		        })
			]
		});
		
		// FORM PANEL
		var oForm = new Ext.form.FormPanel({
		    layout			: 'tableform',
			layoutConfig	: {columns : 3},
			labelWidth		: 160,
			monitorResize 	: true,
			style			: 'padding: 30px;',
			border			: false,
			autoHeight		: true,
			region			: "center",
			buttonAlign		: 'right',
			items			: [
				oAnagraphicFieldSet,
				oLoginFieldset,
				oRegFieldset,
				oDisclaimerFieldset,
				oObj.fields.oDisc_AcceptCheckBox
			],
			buttons			: [{
				text	: 'Invia richiesta',
				iconCls	: 'send',
				handler	: function(){
					if(oObj.validateForm()){
						oObj.saveRegistration();
					}
				}
			}]
		});
		
		return oForm;
	}
	
	/* GRID PANEL PER GLI ANALITI DI OGNI PROFILO */
	this.buildAnalytesGrid = function(){
		var oObj = this;
		
		var oStore =  new Ext.data.JsonStore({
			root		: '',
			fields		: ['description']
		});
		oStore.loadData([{description : "Cliccare sul nome di un profilo per vedere i suoi analiti."}]);
	  	    
	    var oCM =  new Ext.grid.ColumnModel([
			{header: "Descrizione", dataIndex: "description"}
		]);
		
		var oToolbar = new Ext.Toolbar({
			height		: 27,
	    	style		:'padding:5px',
			items		:[getFormattedString("VEQ - Lista degli analiti presenti nel profilo")]
		});
		
		var oGrid = new Ext.grid.GridPanel({
			tbar				: oToolbar,
			height				: 200,
			viewConfig			: {autoFill : true,forceFit : true},
			stripeRows			: true,
			loadMask			: {msg:"Caricamento in corso..."},
			colspan				: 2,
			collapsed			: true,
			store				: oStore,
			autoScroll			: true,
	    	style				:'margin-left:5px;margin-top:5px',
			cm					: oCM
		});
		return oGrid;
	}
	
	/* GRID PANEL PER LE ISCRIZIONI AI PROFILI */
	this.buildProfileGrid = function(){
		var oObj = this;
		
		var oStore =  new Ext.data.JsonStore({
			url: "actions/RegistrationActions.php",
			baseParams	: {
				noCache	: new Date(),
				action	: 'getProfiles'
			},
			root		: '',
			fields		: ['code','description','subscribe','category']
		});
		oStore.load();
	   	    
	    var oCheckColumn = new Ext.grid.CheckColumn({
			header: 'Iscriviti',
			dataIndex: 'subscribe',
			width: 20,
			click : function(oCheckBox, oRecord){
				if (oRecord.data.category == "chimica-clinica"){
					for (var i = 0; i<oStore.getCount(); i++){
						var oTmpRec = oStore.getAt(i);
						if(oTmpRec.data.category == "chimica-clinica" && oTmpRec.get('subscribe') != oRecord.data.subscribe){
							oTmpRec.set('subscribe', oRecord.data.subscribe);
							oTmpRec.commit();
						}
					}
				}
			}
		});
	    
	    var oCM =  new Ext.grid.ColumnModel([
			{header: "Profilo", dataIndex: "description"},
			oCheckColumn
		]);
		
		var oToolbar = new Ext.Toolbar({
			height		: 27,
	    	style		:'padding:5px',
			items		:[getFormattedString("VEQ - Iscrizione ai profili")]
		});
		
		var oGrid = new Ext.grid.GridPanel({
			tbar				: oToolbar,
			plugins				: oCheckColumn,
			height				: 200,
			viewConfig			: {autoFill : true,forceFit : true},
			stripeRows			: true,
			loadMask			: false,
			collapsed			: true,
			colspan				: 2,
	    	style				:'margin-right:5px;margin-top:5px',
			store				: oStore,
			autoScroll			: true,
			cm					: oCM,
			listeners			: {
				cellclick	: function(oGrid,nRow,nCol){
					if(nCol == 0){
						var sCode = oGrid.getStore().getAt(nRow).data.code;
						oObj.oReg_AnalytesGrid.loadMask.show();
						Ext.Ajax.request({
							url		: 'actions/RegistrationActions.php',
							method 	: 'POST',
							params	:{
								action	: 'getAnalytes4Profile',
								profile	: sCode,
								noCache	: new Date()
							},
							failure	:function(oResponse){
								serverError(oResponse.responseText);
								oObj.oReg_AnalytesGrid.loadMask.hide();
							},
							success	: function(oResponse){
								var oData = Ext.decode(oResponse.responseText);
								oObj.oReg_AnalytesGrid.getStore().loadData(oData);
								oObj.oReg_AnalytesGrid.loadMask.hide();
							}
						});
					}
				}
			}
		});
		return oGrid;
	}
	
	/* CREAZIONE DEI VARI FIELDS PER I FIELDSETS */
	this.buildFields = function(){
		var oObj = this;
		
		// Fields richiesti dal pannello del tipo di ente
		var oAn_PublicType =  new Ext.form.Checkbox({
            anchor			: '100%',
            fieldLabel		: 'Tipo di ente:',
			boxLabel		: '&nbsp;&nbsp;Pubblico',
			listeners		: {
				check 	: function(oCheckBox,bIsChecked){
					if(bIsChecked){
						oAn_PrivateType.setValue(false);
					} else {
						oAn_PrivateType.setValue(true);
					}
				}
			}
        });
	        
		var oAn_PrivateType =  new Ext.form.Checkbox({
            anchor			: '100%',
			boxLabel		: '&nbsp;&nbsp;Privato',
			listeners		: {
				check 	: function(oCheckBox,bIsChecked){
					if(bIsChecked){
						oAn_PublicType.setValue(false);
					} else {
						oAn_PublicType.setValue(true);
					}
				}
			}
        });
		
		// FIELDS PER L'ANAGRAFICA
		this.fields.oAn_Name = new Ext.form.TextField({
            fieldLabel		: 'Denominazione laboratorio',
            anchor			: '100%',
            paramName		: 'name',
			fieldName		: 'oAn_Name',
			isRequired		: true,
			saveMe			: true,
			isValid			: function(){
				if (this.getValue() !== ''){
					return true;
				} else {
					return false;
				}
			}
        });
        
        this.fields.oAn_ReferencePerson = new Ext.form.TextField({
            fieldLabel		: 'Persona di riferimento',
            paramName		: 'ref_person',
            anchor			: '100%',
			fieldName		: 'oAn_ReferencePerson',
			isRequired		: true,
			saveMe			: true,
			isValid			: function(){
				if (this.getValue() !== ''){
					return true;
				} else {
					return false;
				}
			}
        });
        
        this.fields.oAn_Address = new Ext.form.TextField({
            fieldLabel		: 'Indirizzo',
			fieldName		: 'oAn_Address',
            paramName		: 'address',
            anchor			: '100%',
			isRequired		: true,
			saveMe			: true,
			isValid			: function(){
				if (this.getValue() !== ''){
					return true;
				} else {
					return false;
				}
			}
        });
        
        this.fields.oAn_City = new Ext.form.TextField({
            fieldLabel		: 'Citt&agrave;',
			fieldName		: 'oAn_City',
            paramName		: 'city',
            anchor			: '100%',
			saveMe			: true,
			isRequired		: true,
			isValid			: function(){
				if (this.getValue() !== ''){
					return true;
				} else {
					return false;
				}
			}
        });
        
        this.fields.oAn_Province = new Ext.form.TextField({
            fieldLabel		: 'Provincia',
            fieldName		: 'oAn_Province',
            paramName		: 'province',
            anchor			: '100%',
			isRequired		: true,
			saveMe			: true,
			isValid			: function(){
				if (this.getValue() !== ''){
					return true;
				} else {
					return false;
				}
			}
        });
        
        this.fields.oAn_CAP = new Ext.form.TextField({
            fieldLabel		: 'CAP',
            anchor		: '100%',
            fieldName		: 'oAn_CAP',
            paramName		: 'cap',
			isRequired		: true,
			saveMe			: true,
			isValid			: function(){
				if (this.getValue() !== ''){
					return true;
				} else {
					return false;
				}
			}
        });
        
        this.fields.oAn_Phone = new Ext.form.TextField({
            fieldLabel		: 'Telefono',
            anchor			: '100%',
            paramName		: 'phone',
			fieldName		: 'oAn_Phone',
			isRequired		: true,
			saveMe			: true,
			isValid			: function(){
				if (this.getValue() !== ''){
					return true;
				} else {
					return false;
				}
			}
        });
        
        this.fields.oAn_Mail = new Ext.form.TextField({
            fieldLabel		: 'E-mail',
            anchor			: '100%',
			fieldName		: 'oAn_Mail',
            paramName		: 'mail',
            vtype			: 'email',
			saveMe			: true,
			isRequired		: true,
			isValid			: function(){
				if (this.getValue() !== ''){
					return true;
				} else {
					return false;
				}
			}
        });
        
        this.fields.oAn_OfficialName = new Ext.form.TextArea({
            fieldLabel		: 'Denominazione per documenti/attestati',
			saveMe			: true,
			fieldName		: 'oAn_OfficialName',
            paramName		: 'official_name',
            anchor			: '100%'
        });
        
        this.fields.oAn_Type = new Ext.form.CheckboxGroup({
            anchor			: '100%',
            fieldLabel		: 'Tipo di ente',
            paramName		: 'type',
            xtype			: 'checkboxgroup',
			fieldName		: 'oAn_Type',
            fieldType		: 'checkbox',
			labelWidth		: 160,
			columns 		: 1,
            items			: [oAn_PublicType,oAn_PrivateType],
			isRequired		: true,
			saveMe			: true,
            isValid			: function(){
            	if(oAn_PrivateType.getValue() === true || oAn_PublicType.getValue() === true){
            		return true;
            	}
            	return false;
            },
            getValue 		: function(){
            	if(oAn_PrivateType.getValue() === true){
            		return 'private';
            	} else {
            		return 'public';
            	}
            }
        });
        
        // FIELDS PER LE ISCRIZIONI
        this.fields.oReg_IsOurCustomer = new Ext.form.Checkbox({
            anchor			: '100%',
            hideLabel		: true,
            fieldType		: 'checkbox',
			fieldName		: 'oReg_IsOurCustomer',
			boxLabel		: '&nbsp;&nbsp;Si dispone di un cod. cliente Medical Systems?',
			listeners		: {
				check 	: function(oCheckBox,bIsChecked){
					if(bIsChecked){
						oObj.fields.oReg_CustomerCode.enable();
					} else {
						oObj.fields.oReg_CustomerCode.disable();
					}
				}
			}
        });
        
		this.fields.oReg_CustomerCode = new Ext.form.TextField({
            fieldLabel		: 'Codice cliente',
            hideLabel		: true,
			saveMe			: true,
            anchor			: '100%',
            paramName		: 'customer_code',
            emptyText		: 'Inserire codice cliente...',
            disabled		: true,
			fieldName		: 'oReg_CustomerCode',
			isRequired		: true,
			isValid			: function(){
				if(oObj.fields.oReg_IsOurCustomer.getValue() !== true){
					return true;
				} else if (this.getValue() !== ''){
					return true;
				} else {
					return false;
				}
			}
        });
		
		this.fields.oReg_VEQCheckBox = new Ext.form.Checkbox({
            anchor			: '100%',
			hideLabel		: true,
			saveMe			: true,
            fieldType		: 'checkbox',
            paramName		: 'veq_reg',
			fieldLabel		: 'Iscrizione VEQ',
			boxLabel		: '&nbsp;&nbsp;Iscrivimi al programma VEQ',
			isRequired		: true,
			fieldName		: 'oReg_VEQCheckBox',
			listeners		: {
				check 	: function(oCheckBox,bIsChecked){
					if(bIsChecked){
						oObj.oReg_ProfilesGrid.expand(false);
						oObj.oReg_AnalytesGrid.expand(false);
					} else {
						oObj.oReg_ProfilesGrid.collapse(false);
						oObj.oReg_AnalytesGrid.collapse(false);
					}
				}
			}
        });
        
        this.fields.oReg_CQICheckBox = new Ext.form.Checkbox({
            anchor			: '100%',
            fieldType		: 'checkbox',
			hideLabel		: true,
            paramName		: 'cqi_reg',
			saveMe			: true,
			fieldLabel		: 'Iscrizione CQI',
			boxLabel		: '&nbsp;&nbsp;Iscrivimi al programma CQI',
			fieldName		: 'oReg_CQICheckBox',
			isRequired		: true
        });
        
        // FIELDS PER I DATI DI ACCESSO AL SITO
        this.fields.oSite_Login = new Ext.form.TextField({
            fieldLabel		: 'Login',
			saveMe			: true,
            anchor			: '100%',
            paramName		: 'login',
			fieldName		: 'oSite_Login',
			isRequired		: true,
			isValid			: function(){
				if(oObj.fields.oReg_IsOurCustomer.getValue() !== true){
					return true;
				} else if (this.getValue() !== ''){
					return true;
				} else {
					return false;
				}
			}
        });
        
        this.fields.oSite_Password = new Ext.form.TextField({
            fieldLabel		: 'Password',
			saveMe			: true,
            paramName		: 'password',
            inputType		: 'password',
            anchor			: '100%',
			fieldName		: 'oSite_Password',
			isRequired		: true,
			isValid			: function(){
				if (this.getValue() !== ''){
					return true;
				} else {
					return false;
				}
			}
        });
        
        this.fields.oSite_Password2 = new Ext.form.TextField({
            fieldLabel		: 'Conferma password',
            inputType		: 'password',
            anchor			: '100%',
			fieldName		: 'oSite_Password2',
			isRequired		: true,
			isValid			: function(){
				if (this.getValue() !== ''){
					return true;
				} else {
					return false;
				}
			}
        });
        
        // FIELDS PER IL DISCLAIMER
        this.fields.oDisc_AcceptCheckBox = new Ext.form.Checkbox({
            anchor			: '100%',
            fieldType		: 'checkbox',
            colspan			: 2,
			hideLabel		: true,
			fieldLabel		: 'Accettazione disclaimer',
			boxLabel		: '&nbsp;&nbsp;<b style = "color:#15428B;font-weight:900;">Prendo visione e accetto integralmente tutte le condizioni riportate nel Disclaimer.</b>',
            isRequired		: true,
			fieldName		: 'oDisc_AcceptCheckBox',
			isValid			: function(){
				return this.getValue();
			}				
        });
	}
	
	/* CONTROLLO SUL FORM */
	this.validateForm = function(){
		
		var bIsValid = true;
		var bReg_VEQ_CQI_AlreadyChecked = false;
		var bSite_Password_AlreadyChecked = false;
		var sInvalidMsg = "";
		var sInvalidMsgFooter = "";
		
		var oFields = this.fields;
		for (var item in oFields){
			var oField = this.fields[item];
			if(oField.isRequired){
				switch (oField.fieldName){
					case 'oReg_CQICheckBox':
					case 'oReg_VEQCheckBox':
						if(!bReg_VEQ_CQI_AlreadyChecked){
							bReg_VEQ_CQI_AlreadyChecked = true;
							if(this.fields.oReg_CQICheckBox.getValue() === false && this.fields.oReg_VEQCheckBox.getValue() === false){
								bIsValid = false;
								sInvalidMsgFooter += "<b>Bisogna selezionare almeno un iscrizione tra VEQ e CQI</b>,<br/>";
							}
							if(oField.fieldName === 'oReg_VEQCheckBox' && oField.getValue() === true){
								var oStore = this.oReg_ProfilesGrid.getStore();
								var bSelectionFound = false;
								for (var i = 0; i < oStore.getCount() ; i++){
									if(oStore.getAt(i).data.subscribe == true){
										bSelectionFound = true;
										break;
									}
								}
								if(!bSelectionFound){
									bIsValid = false;
									sInvalidMsgFooter += "<b>Bisogna iscriversi ad almeno un profilo</b>,<br/>";
								}
							}
						}
					break;
					
					case 'oSite_Password':
					case 'oSite_Password2':
						if(!bSite_Password_AlreadyChecked){
							bSite_Password_AlreadyChecked = true;
							if(!oField.isValid()){
								bIsValid = false;
								sInvalidMsg += "<b>Il campo <span style='color:E21515;'>Password</span> non &egrave; stato inserito</b>,<br/>";
							} else if (this.fields.oSite_Password.getValue() !== this.fields.oSite_Password2.getValue()){
								bIsValid = false;
								sInvalidMsgFooter += "<b>Le password inserite non corrispondono</b>,<br/>";
							}
						}
					break;
					
					case 'oAn_CAP':
						if(!oField.isValid(true)){
							bIsValid = false;
							sInvalidMsg += "<b>Il campo <span style='color:E21515;'>" + oField.fieldLabel + "</span> non &egrave; stato inserito</b>,<br/>";
						} else if((oField.getValue() + "").length != 5){
							bIsValid = false;
							sInvalidMsgFooter += "<b>Il CAP non &egrave; stato inserito correttamente</b>,<br/>";
						}
					break;
					
					case 'oReg_CustomerCode':
						if(this.fields.oReg_IsOurCustomer.getValue() === true){
							if(!oField.isValid(true)){
								bIsValid = false;
								sInvalidMsg += "<b>Il campo <span style='color:E21515;'>" + oField.fieldLabel + "</span> non &egrave; stato inserito</b>,<br/>";
							} else if(oField.getValue().length != 6){
								bIsValid = false;
								sInvalidMsgFooter += "<b>Il Codice cliente non &egrave; stato inserito correttamente</b>,<br/>";
							} else if(!this.validateCustomerCode(oField.getValue())){
								bIsValid = false;
								sInvalidMsgFooter += "<b>Il Codice cliente non &egrave; stato inserito correttamente</b>,<br/>";
							}
						}
					break;
					
					default:
						if(!oField.isValid(true)){
							bIsValid = false;
							switch(oField.fieldType){
								case "checkbox":
									sInvalidMsg += "<b>Il campo <span style='color:E21515;'>" + oField.fieldLabel + "</span> non &egrave; stato selezionato</b>,<br/>";
								break;
								default:
									sInvalidMsg += "<b>Il campo <span style='color:E21515;'>" + oField.fieldLabel + "</span> non &egrave; stato inserito</b>,<br/>";
								break;
							}
						}
					break;
				}
			}
		}
		
		if (!bIsValid){
			var sMsg = sInvalidMsg + sInvalidMsgFooter;
			Ext.Msg.show({
				msg: sMsg.substring(0,sMsg.length -6),
				resizable: false,
				title: "<b>Ci sono i seguenti errori nella pagina:</b>",
				buttons: Ext.Msg.OK,
				height: 10,
				width: 360,
				modal: true
			});
		}
		
		return bIsValid;
	}
	
	/* VALIDAZIONE DEL CODICE CLIENTE */
	this.validateCustomerCode = function(sCustomerCode){
		var sStringPart = sCustomerCode.substring(0,2);
		var sNumericPart = sCustomerCode.substring(2,6);
		var bIsValid = true;
		var Char = null;
	 
	 	// Controllo sulla parte iniziale (2 caratteri)
		for (i = 0; i < sStringPart.length && bIsValid == true; i++){
			Char = sStringPart.charAt(i);
			if ("|!£$%&()=?^[]@#°_0123456789+-*/àèìòù.:,;<>€'\\\"\t\n".indexOf(Char) != -1){
	        	bIsValid = false;
	        }
	   	}
	   	
	   	// Controllo sulla parte finale (4 numeri)
		for (i = 0; i < sNumericPart.length && bIsValid == true; i++){
			Char = sNumericPart.charAt(i); 
			if ("0123456789".indexOf(Char) == -1){
	        	bIsValid = false;
	        }
	   	}
	   	return bIsValid;
	}
	
	/* SALVATAGGIO DEI DATI */
	this.saveRegistration = function(){
		var oObj = this;
		
		var aParameters = {
			noCache	: new Date(),
			action	: 'saveRegistration'
		};
		
		var oFields = this.fields;
		for (var item in oFields){
			var oField = this.fields[item];
			if(oField.saveMe){
				aParameters[oField.paramName] = oField.getValue();
				if(oField.fieldName == 'oReg_VEQCheckBox'){
					var sProfiles = "";
					if(oField.getValue() == true){
						for (var i = 0 ; i < this.oReg_ProfilesGrid.getStore().getCount() ; i++){
							var oData = this.oReg_ProfilesGrid.getStore().getAt(i).data;
							if(oData.subscribe == true){
								sProfiles += oData.code + "$$$";
							}
						}
					}
					aParameters.profiles = sProfiles.substring(0,sProfiles.length -3);
				}
			}
		}
		//describe(aParameters);
		
		Ext.Ajax.request({
			url		: 'actions/RegistrationActions.php',
			method 	: 'POST',
			params	: aParameters,
			failure	: function(oResponse){
				Ext.Msg.show({
					msg: oResponse.responseText,
					resizable: true,
					title: "<b>Errore grave</b>",
					buttons: Ext.Msg.OK,
					height: 200,
					width: 250,
					modal: true,
					icon: Ext.MessageBox.ERROR
				});
			},
			success	: function(oResponse){
				var oData = Ext.decode(oResponse.responseText);
				//alert(oData.success + " - " + typeof(oData.success));
				if(oData.success){
					Ext.MessageBox.alert(						
						//'Richiesta effettuata',
                                                "<b>Richiesta effettuata</b>",
                                                oObj.sFinalMsg,
						function() {
							location.href='login.php';
						}
					);
				} else {
					Ext.Msg.show({
						msg: oData.error,
						resizable: true,
						title: "<b>Errore durante il salvataggio</b>",
						buttons: Ext.Msg.OK,
						height: 70,
						width: 250,
						modal: true,
						icon: Ext.MessageBox.ERROR
					});
				}
			}
		});
	}
}
