// JavaScript Document



// funzione per riempire gli input con Int 

var v = new Array();
v["username"] = 'Utente'; // [nome del campo] = 'descrizione che volete compaia all'interno del campo'
v["password"] = 'Password';
v["testo_rtf"] = 'Scrivi qui il tuo messaggio è necessario essere registrato';
v["nome"] = 'Nome';
v["cognome"] = 'Cognome';
v["email"] = 'Email';
v["testo"] = 'Messaggio';

var iconPath = '/extjs/resources/images/silk/icons/';

var Config = {
	TIPO_UTENTE: '',
	TIPO_UTENTE_PROD: 'A',
	TIPO_UTENTE_FORN: 'P',
	TIPO_UTENTE_ADMIN: 'ADON',
	TIPO_RICHIESTA_PROD: 'D',
	TIPO_RICHIESTA_FORN: 'O'
};
    
var statoRenderer = function (val, meta, r, mini) {
	var ret = "";
    if (val == "In attesa") {
    	ret = '<img alt="' + val + '" src="/img/red.png" title="' + val + '">';
    } else if (val == "Accettata") {
    	ret = '<img alt="' + val + '" src="/img/yellow.png" title="' + val + '">';
    } else {
    	ret = '<img alt="' + val + '" src="/img/green.png" title="' + val + '">';
    }
    return '<div qtip="' + val + '">' + ret + '</div>';
}

var statoRenderer16 = function (val, meta, r, mini) {
	var ret = "";
    if (val == "In attesa") {
    	ret = '<img alt="' + val + '" src="/img/red16.png" title="' + val + '">';
    } else if (val == "Accettata") {
    	ret = '<img alt="' + val + '" src="/img/yellow16.png" title="' + val + '">';
    } else if (val == "Accreditata") {
    	ret = '<img alt="' + val + '" src="/img/green16.png" title="' + val + '">';
    }
    return '<div qtip="' + val + '">' + ret + '</div>';
}  

var connessioniRenderer = function (val, meta, r) {
    if (val.Accreditata > 0 || val.Accettata > 0) {
      var qtip = "<b>" + ((r.get('tipo') == "D") ? 'Offerte compatibili' : 'Domande compatibili') + "</b><br />";
      if (val.Accreditata > 0) {
        qtip += '<div><img src=\'/img/green16.png\'>Accreditate: ' + val.Accreditata + '</div>';
      }
      if (val.Accettata > 0) {
        qtip += '<div><img src=\'/img/yellow16.png\'>Accettate: ' + val.Accettata + '</div>';
      }
      val = '<img ext:qtip="' + qtip + '" src="/img/connected.png">';
    } else {
      val = '<img src="/img/notconnected.png">';
    }
    return val;
}

var tipoRichiestaRenderer = function (val, meta, r) {
    if (val == "D") {
      val = '<img src="/img/magazzino.png" ext:qtip="Produttore">';
    } else {
      val = '<img src="/img/camion.png" ext:qtip="Fornitore">';
    }
    return val;
}

var statoRichiedenteRenderer = function (val, meta, r, mini) {
	var ret = "";
    if (val == "V") {
    	ret = '<img alt="' + val + '" src="/img/green.png" title="Attivo">';
    }  else {
    	ret = '<img alt="' + val + '" src="/img/red.png" title="Inattivo">';
    }
    return '<div qtip="' + val + '">' + ret + '</div>';
}

var tipoRichiedenteRenderer = function (val, meta, r) {
    if (val == "P") {
      val = '<img src="/img/camion.png" ext:qtip="Fornitore">';
    } else {
      val = '<img src="/img/magazzino.png" ext:qtip="Produttore">';
    }
    return val;
}

var qtaRenderer = function (val, meta, r) {
	if (val != 0 && val != '') {
    	val = '<b style="font-size: 12px">' + numSYStoIT(val) + 'Kg</b>';
    	val += '<br /><span style="font-size: 10px">(' + numSYStoIT(r.get('QUANTITA_MC')) + 'mc)</span>';
	}
    return val;
}

var qtaMediaRenderer = function(val, meta, r) {
	if (val != 0 && val != '') {
        val = numSYStoIT(val) + 'Kg';
	}
    return val;    	  
}

var analisiOkRenderer = function(val, meta, r) {
    return val ? 'Sì' : 'No';    	  
}

var ageRenderer = function (v) {
    var s = v * 1;
    var g = Math.floor(s / 86400);
    s -= g * 86400;
    var h = Math.floor(s / 3600);
    s -= h * 3600;
    var m = Math.floor(s / 60);
    s -= m * 60;
    v = "";
    if (g > 0) {v += g + " giorni "}
    if (h > 0) {v += h + " ore "}
    if (m > 0 && g == 0) {v += m + " minuti "}
    return v;
}  

var euroRenderer = function (v, prefix) {
	if (!prefix)
		prefix = '&euro;';
    v = (Math.round((v-0)*100))/100;
    v = (v == Math.floor(v)) ? v + ".00" : ((v*10 == Math.floor(v*10)) ? v + "0" : v);
    v = String(v);
    var ps = v.split('.');
    var whole = ps[0];
    var sub = ps[1] ? ','+ ps[1] : ',00';
    var r = /(\d+)(\d{3})/;
    while (r.test(whole)) {
      whole = whole.replace(r, '$1' + '.' + '$2');
    }
    v = whole + sub;
    if(v.charAt(0) == '-'){
      return '-' + prefix + ' ' + v.substr(1);
    }
    return prefix + " " +  v;
}

var dettaglioRichiestaRenderer = function (val, meta, r) {
    if (Config.TIPO_UTENTE && (r.get('STATO') == 'Accreditata' || Config.TIPO_UTENTE == Config.TIPO_UTENTE_ADMIN || (r.get('STATO') != 'Accreditata' && r.get('MINE')))) {
      val = "<b>" + val + "</b><br><i>" + r.get('TITOLO') + "</i><br />" + r.get('INDIRIZZO');
      if (r.get('COMUNE')) {
    	  val += ', ' + r.get('COMUNE') + (r.get('CAP') ? ' - ' + r.get('CAP') : '') + '<br />';       	  
      }
      else {
    	  val += '<br>';
      }
      if (r.get('TEL')) {
    	  val += '<img src="' + iconPath + '/telephone.png"> ' + r.get('TEL')
      }
      if (r.get('FAX')) {
    	  val += ' <img src="' + iconPath + '/printer.png"> ' + r.get('FAX');
      }
      if (r.get('EMAIL')) {
    	  val += ' <img src="' + iconPath + '/email.png"> ' + r.get('EMAIL');
      }
      if (r.get('NOTE')) {
    	  var qtip = r.get('NOTE').replace(/"/ig, "&quot;").replace(/'/ig, "&apos;");
    	  val = '<div qtip="' + qtip + '">' + val + '</div>';
      }
    } else {
      val =  "<i>" + r.get('TITOLO') + "</i><br />(Dati anagrafici non visibili)";
    }
    return val;
}

var contatoreRigheRenderer = function (val, meta, r) {
	var ret = val;
	if (r.get('N_TOT')) {
		ret = val + '/' + r.get('N_TOT');
	}
    return ret;
}

var qtipRenderer = function (val, meta, r) {
	  var ret = val;
	  if (ret) {
		  var qtip = ret.replace(/"/ig, "&quot;").replace(/'/ig, "&apos;");
		  ret = '<div qtip="' + qtip + '">' + ret + '</div>';			  
	  }
	  return ret;
}

Ext.override(Ext.data.JsonReader,
{
	    realize: function(rs, data){
	        if (Ext.isArray(rs)) {
	            for (var i = rs.length - 1; i >= 0; i--) {
	                // recurse
	                if (Ext.isArray(data)) {
	                    this.realize(rs.splice(i,1).shift(), data.splice(i,1).shift());
	                }
	                else {
	                    // weird...rs is an array but data isn't??  recurse but just send in the whole invalid data object.
	                    // the else clause below will detect !this.isData and throw exception.
	                    this.realize(rs.splice(i,1).shift(), data);
	                }
	            }
	        }
	        else {
	            // If rs is NOT an array but data IS, see if data contains just 1 record.  If so extract it and carry on.
	            if (Ext.isArray(data) && data.length == 1) {
	                data = data.shift();
	            }
	            if (!this.isData(data)) {
	                // TODO: Let exception-handler choose to commit or not rather than blindly rs.commit() here.
	                //rs.commit();
	                throw new Ext.data.JsonReader.Error('realize', rs);
	            }
	            rs.phantom = false; // <-- That's what it's all about
	            rs._phid = rs.id;  // <-- copy phantom-id -> _phid, so we can remap in Store#onCreateRecords
	            rs.id = this.getId(data);
	            rs.data = data;
	            
	            var map = rs.store.data.map[rs._phid];
	            // update keys array (bug with selection)
	            for(var i=0; i<rs.store.data.keys.length; i++) {
	                if (rs.store.data.keys[i] == rs._phid) {
	                   rs.store.data.keys[i] = map.id;
	                   break;
	                }
	            }
	            rs.store.data.map[rs.id] = map;
	            delete rs.store.data.map[rs._phid];
	            rs.commit();
	        }
	    }
});   

function richiestaPreview(efRichiesta) {
  	var previewWin = new Ext.Window({
  		id: 'richiestaPreviewWin',
  		width: 950,
  		height: 650,
  		modal: true,
  		items: [{
  			xtype: 'panel',
	    		width: 920,
	    		height: 620,
	    		border: false,
  			html: '<iframe src="/adon.pl?act=Env&Mode=RichiestaPreview&ID=' + efRichiesta.get('ID') + '" width="100%" height="100%" frameborder="0" scrolling="auto"></iframe>'
  		}],
  		buttons: [{
	  	    icon: iconPath + '/world.png',
	  	    cls:"x-btn-text-icon",                 
	  	    text: 'Visualizza in una nuova finestra',
	  	    tooltip: 'Visualizza il riepilogo in una nuova finestra del browser',
	  	    listeners: {
	  	    	click: function() {
	  	    		window.open('/adon.pl?act=Env&Mode=RichiestaPreview&ID=' + efRichiesta.get('ID'), 'AnteprimaRichiesta', "status=yes,menubar=yes,toolbar=yes");
	  	    		previewWin.close();
	  	    	}
	  	    }
	  	},{
	  	    icon: iconPath + '/cancel.png',
	  	    cls:"x-btn-text-icon",                 
	  	    text: 'Chiudi',
	  	    tooltip: 'Chiudi la finestra',
	  	    listeners: {
	  	    	click: function() {
	  	    		previewWin.close();
	  	    	}
	  	    }
	  	}]
  	});
  	previewWin.show();	
}

Ext.ux.SimpleEditingGridPanel = Ext.extend(Ext.grid.GridPanel, {         
    constructor: function(config) {
		/*
		 	checkMode viene attivato automaticamente specificando un checkStore, in tal caso i dati editati sono quelli dello checkStore (cfr. nota)
		 	la modalità di funzionamento checkMode (true o false) non deve essere modificata dopo la inizializzazione
		 	
		    nuovi elementi di configurazione
		    --------------------------------
			checkStore		store contenente i record che determinano la selezione corrente dentro lo store della grid
			checkField		campo dei record in checkStore utilizzato per fare match con quelli della grid (es: ID_TIPO in checkStore che matcha ID in store)
			checkHeader		stringa html che formatta l'header della colonna dei check
			checkOnly		false per consentire il check con click su qualsiasi cella della riga
			newRecord		valori predefiniti per l'inserimento di un nuovo record
			loadMaskMsg		testo del messaggio in fase di caricamento dati
			canAdd			indica se possibile aggiungere record
			canEdit			indica se possibile modificare record
			canDel			indica se possibile eliminare record
			buttonAdd		template proprietà per il pulsante Add
			buttonDel		template proprietà per il pulsante Del
			buttonRefresh	template properità per il pulsante di refresh
			hideButtonLabel indica se nascondere le etichette dei pulsanti	
			beforeEdit		funzione da chiamare prima di attivare l'editing, se ritorna false l'editing viene annullato	
			afterEdit		funzione da chiamare dopo che l'editing è terminato
			checkDel		funzione che ritorna true se il record selezionato è eliminabile
			errorSummary	indica se visualizzare l'elenco degli errori di inserimento
			
			n.b: il checkStore se presente è quello utilizzato per le operazioni di scrittura record, mentre store viene utilizzato per determinare il set di possibili scelte
				 tipicamente il checkStore è associato ad una tabella di incrocio mentre lo store a una delle due tabelle incrociate
				 in newRecord si fissa il valore di una delle due tabelle in modo che si realizzi l'editing della seconda tabella di incrocio rispetto a un valore fisso della prima
				 es: se la tabella di incrocio fra GRUPPI e TIPI è GRUPPI_TIPI: (ID, ID_TIPO, ID_GRUPPO) e newRecord: {ID_GRUPPO: 10} allora si ha l'editing di tutti i tipi del gruppo 10

		 	proprietà da usare in lettura/scrittura (R/W)
		 	---------------------------------------------
		 	newRecord		R/W
		 	checkField		R/W
		 	checkMode		R
		 	canAdd			R
		 	canEdit			R
		 	canDel			R
		 	
		 	nuovi metodi
		 	---------------------------------------------
		 	setEnabled
		 	getCheckStore
		 	setFilter
		 	setFilterBy
		 	clearFilter		 	
		*/
		this.checkStore = config.checkStore; // lo store utilizzato identificare le righe da spuntare, mentre store contiene tutte le possibili righe	
		this.checkField = config.checkField ? config.checkField : 'ID';
		this.checkFieldSet = config.checkFieldSet ? config.checkFieldSet : null,
		this.checkMode = config.checkStore ? true : false;
	    this.rowEditorPluginIdx = 0;
	    this.newRecord = config.newRecord ? config.newRecord : {DESCRIZIONE: ''};
	    this.canEdit = config.canEdit ? config.canEdit : true;
	    this.canAdd = config.canAdd ? config.canAdd : true;
	    this.canDel = config.canDel ? config.canDel : true;
	    this.checkDel = config.checkDel ? config.checkDel : undefined;
	    this.setEnabled = function(action, value) {
	    	if (action.toLowerCase() == 'add') {
	    		this.canAdd = value;
	    		Ext.getCmp(config.id + 'AddButton').setDisabled(!value);
	    	}
	    	else if(action.toLowerCase() == 'edit') {
	    		this.canEdit = value;
	    	}
	    	else if (action.toLowerCase() == 'del') {
	    		this.canDel = value;
	    		Ext.getCmp(config.id + 'DelButton').setDisabled(!value);
	    	}
	    }
	    if (this.checkMode) {
			var gridSel = new Ext.grid.CheckboxSelectionModel({
				isCheckbox: true,
				header: config.checkHeader ? config.checkHeader : '',
			    checkOnly: config.checkOnly === false ? false : true,
				listeners: {
					'rowselect': function(selModel, rowIndex, record) {
						return;
						var grid = selModel.grid;
						if (grid.canAdd) {		
				    		var store = grid.getCheckStore();
			                var idx = store.find(grid.checkField, record.get(grid.getStore().reader.meta.idProperty));
			                if (idx < 0) {
				                var rt = store.recordType;
				                var r = new rt(grid.newRecord);		
				                r.set(grid.checkField, record.get(grid.getStore().reader.meta.idProperty));
				                store.insert(0, r);	
				                store.save();			                	
			                }
						}
					},
					'rowdeselect': function(selModel, rowIndex, record) {
						return;
						if (selModel.grid.canDel) {
							var store = selModel.grid.getCheckStore();
							var rg = store.getRange();
				  			var idx = store.findExact(selModel.grid.checkField, record.get(selModel.grid.getStore().reader.meta.idProperty));
							if (idx >= 0) {
					    		store.remove(store.getAt(idx));
					    		store.save();							
							}								
						}						
					}					
				}
			});
			config.columns.unshift(gridSel);
			config.selModel = gridSel;
	    }
	    if (!config.selModel) {
	    	config.selModel = new Ext.grid.RowSelectionModel({singleSelect: false});
	    }
	    this.removeSelectedRecords = function(confirmText) {
	    	var store = this.getStore();
	    	var records = this.getSelectionModel().getSelections();
	    	if (!records || records.length <= 0 || !this.canDel)
	    		return;	    	
	    	if (!confirmText) {
	    		if (config.buttonDel && config.buttonDel.confirmText) {
	    			confirmText = config.buttonDel.confirmText;
	    		}
	    		else {
	    			confirmText = 'Siete sicuri di voler rimuovere i record selezionati?';	    			
	    		}
	    	}
	    	var dblConfirm = config.buttonDel && config.buttonDel.dblConfirm;
	    	// se la prorietà ID dei record è nulla allora possono essere rimossi senza richiesta di conferma
	    	var noConfirm = true;
	    	for (var i = 0; i<records.length; i++) {
	    		noConfirm = noConfirm && (records[i].phantom);
	    	}
	    	if (!noConfirm && !this.checkMode) {
			  Ext.Msg.confirm('Conferma', confirmText, function(btn, text){
			    if (btn == 'yes'){
			    	if (dblConfirm) {
						  Ext.Msg.confirm('Conferma', 'Siete veramente sicuri di voler procedere con l\'operazione di eliminazione? I dati eliminati non potranno essere recuperati.', function(btn, text){
							    if (btn == 'yes'){
							    	store.remove(records);
							    	store.save(); 							    	
							    }
						  });
			    	}
			    	else {
				    	store.remove(records);
					    store.save();					    				    		
			    	}
			    }
			  });        		
	    	}
	    	else {
	    		store.remove(records);
		    	if (store.writer && store.autoSave) {
			    	store.save();					    		
		    	}
	    	}
	    }	    
		this.updateCheckSelection = function() {
			if (!this.checkMode || !this.rendered)
				return;
	  		var sel = this.getCheckStore().getRange();
	  		var sm = this.getSelectionModel();
	  		var rs = new Array();
	  		var store = this.getStore();
	  		for (var i=0; i<sel.length; i++) {
	  			var r = store.getById(sel[i].get(this.checkField));
				if (!r) {
					var idx = store.findExact(store.reader.meta.idProperty, sel[i].get(this.checkField));
					if (idx >= 0) {
						r = store.getAt(idx);
					}					
				}		  			
	  			if (r) {
	  				rs.push(r);
	  			}
	  		}	  			  	
	  		sm.selectRecords(rs, false);  
		}		
        config.id = config.id ? config.id : 'SimpleEditingGrid' + Math.floor(Math.random()*1000000);      
    	config.loadMask = {msg: config.loadMaskMsg ? config.loadMaskMsg : 'caricamento in corso...', store: config.store};
    	config.plugins = [{
        	// proprietà dell'editor: rowIndex, record, grid
    		id: config.id + '_RowEditor',
        	ptype: 'roweditor',
            saveText: 'Salva',
            cancelText: 'Annulla',
            errorText: 'Attenzione',
            clicksToEdit: 2,
            errorSummary: config.errorSummary ? config.errorSummary : false,
            monitorValid: config.errorSummary ? config.errorSummary : false,
            listeners: {
        		'afteredit': function(me, changes, record, rowIndex) {
    				if (typeof(config.afterEdit) == 'function') {
    					config.afterEdit(me.grid, rowIndex); 
    				}
	        		me.grid.getStore().save();	    					
        		},
        		'canceledit': function(editor, cancelPressed) {
        			if (cancelPressed) {
        				var lgrid = Ext.getCmp(config.id);
        				if (editor.record && editor.record.phantom) {
        					lgrid.getStore().remove(editor.record);
        				}
        			}
        		},
        		'beforeedit': function(me, rowIndex) {
        			// l'editing di riga non deve essere abilitato nella modalità checkMode
        			return me.grid.canEdit && !me.grid.checkMode && (config.beforeEdit ? config.beforeEdit(me.grid, rowIndex) : true);
        		},
        		// changes: {campo1: valore1, campo2: valore2} limitatamente ai campi modificati
        		// record: è il record di dati con i valori prima delle modifica
        		'validateedit': function(me, changes, record, rowIndex) {
        			return me.grid.canEdit && !me.grid.checkMode && (config.validateEdit ? config.validateEdit(me.grid, changes, record, rowIndex) : true);
        		}
        	}
        }];	 
    	var tbarItems = [{ 
	    	xtype: 'button', 
	    	id: config.id + 'AddButton',
	        icon: config.buttonAdd && config.buttonAdd.icon ? config.buttonAdd.icon : iconPath + '/table_row_insert.png',
	        cls: config.buttonAdd && config.buttonAdd.cls ? config.buttonAdd.cls : "x-btn-text-icon",		        
	        text: config.hideButtonLabel ? '' : (config.buttonAdd && config.buttonAdd.text ? config.buttonAdd.text : 'Nuovo'),
	        tooltip: config.buttonAdd && config.buttonAdd.tooltip ? config.buttonAdd.tooltip : 'Nuovo record',
	        disabled: config.canAdd === false || (config.buttonAdd && config.buttonAdd.disabled === true),
	        hidden: (config.buttonAdd && config.buttonAdd.hidden ? config.buttonAdd.hidden : false) || this.checkMode,
	        handler: function() {
	    		var lgrid = Ext.getCmp(config.id);
	    		if (!lgrid.canAdd) {
	    			return;
	    		}
	    		var ok = true;
                if (config.buttonAdd && typeof(config.buttonAdd.click) == 'function') {
                	ok = config.buttonAdd.click();
                }
                if (!ok) {
                	return;
                }
	    		var store = lgrid.getStore();
                var rt = store.recordType;
                var r = new rt(lgrid.newRecord);		                
                lgrid.initialConfig.plugins[lgrid.rowEditorPluginIdx].stopEditing();
                store.insert(0, r);
                lgrid.getView().refresh();
                lgrid.getSelectionModel().selectRow(0);
                lgrid.initialConfig.plugins[lgrid.rowEditorPluginIdx].startEditing(0);  
        	}
    	},{
	        xtype: 'button',  
	        id: config.id + 'DelButton',
	        icon: config.buttonDel && config.buttonDel.icon ? config.buttonDel.icon : iconPath + '/table_row_delete.png',
	    	cls: config.buttonDel && config.buttonDel.cls ? config.buttonDel.cls : "x-btn-text-icon",		        
	    	text: config.hideButtonLabel ? '' : (config.buttonDel && config.buttonDel.text ? config.buttonDel.text : 'Elimina'),
	    	tooltip: config.buttonDel && config.buttonDel.tooltip ? config.buttonDel.tooltip : 'Elimina il record selezionato',
	    	disabled: config.canDel === false || (config.buttonDel && config.buttonDel.disabled === true),
	    	hidden: (config.buttonDel && config.buttonDel.hidden ? config.buttonDel.hidden : false) || this.checkMode,
	        listeners: {
	          'click':  function() {
    			if (Ext.getCmp(config.id)) {
    				var ok = true;	    				
                    if (config.buttonDel && typeof(config.buttonDel.click) == 'function') {
                    	ok = config.buttonDel.click();
                    } 	
	                if (!ok) {
	                	return;
	                }	                    
    				Ext.getCmp(config.id).removeSelectedRecords();   				
    			}		    	  
	          }
	        }
	    },{
	        xtype: 'button',  
	        id: config.id + 'RefreshButton',
	        icon: config.buttonRefresh && config.buttonRefresh.icon ? config.buttonRefresh.icon : iconPath + '/table_refresh.png',
	    	cls: config.buttonRefresh && config.buttonRefresh.cls ? config.buttonRefresh.cls : "x-btn-text-icon",		        
	    	text: config.hideButtonLabel ? '' : (config.buttonRefresh && config.buttonRefresh.text ? config.buttonRefresh.text : 'Ricarica'),
	    	tooltip: config.buttonRefresh && config.buttonRefresh.tooltip ? config.buttonRefresh.tooltip : 'Ricarica i dati',
	    	hidden: (config.buttonRefresh && config.buttonRefresh.hidden ? config.buttonRefresh.hidden : false) || this.checkMode,
	        listeners: {
	          'click':  function() {
	    		config.store.reload();
	          }
	        }
	    }];
    	if (!config.tbar) {
    		config.tbar = new Ext.Toolbar();
    	}
    	else if (!config.tbar.items) {
    		config.tbar = new Ext.Toolbar({items: config.tbar});    		
    	}
    	if (config.hideButtonLabel && config.tbar.items) {
        	config.tbar.items.each(function(item) {
        		if (item.getText) {
        			item.setText('');
        		}
        	});    		
    	}
		for (var i=0; i<tbarItems.length; i++) {
    		config.tbar.add(tbarItems[i])
		}
    	config.tbar.setVisible(!this.checkMode || config.tbar.items.getCount() > tbarItems.length);
    	
    	if(!config.bbar && config.pageSize) {
    		config.store.baseParams['start'] = 0;
    		config.store.baseParams['limit'] = config.pageSize;
    		config.bbar = new Ext.PagingToolbar({
                store: config.store,
                pageSize: config.pageSize,
                displayInfo: true,
                displayMsg: 'Record {0} - {1} di {2}',
                emptyMsg: "Nessun record"
            });
    	}
    	
    	if (!config.listeners) {
    		config.listeners = {};
    	}
    	config.listeners.keydown = function(e) {
  	    	if (e.keyCode == Ext.EventObject.DELETE) {
  	    		if (Ext.getCmp(config.id)) {
  	    			var grid = Ext.getCmp(config.id);
  	    			if (grid.canDel && typeof(grid.checkDel) == 'undefined' || (typeof(grid.checkDel) == 'function' && grid.checkDel())) {
  	  	    			Ext.getCmp(config.id).removeSelectedRecords();  	    				
  	    			}
  	    		}  	    			
  	    	}
  	    } 
    	config.listeners.render = function(grid) {
    		if (this.checkMode) {
        		config.checkStore.addListener('load', function() {if (Ext.getCmp(config.id)) {Ext.getCmp(config.id).updateCheckSelection()}});
        		config.checkStore.addListener('datachanged', function() {if (Ext.getCmp(config.id)) {Ext.getCmp(config.id).updateCheckSelection()}});
        	}    		  		
    	}
    	config.listeners.cellclick = function(grid, rowIndex, columnIndex, e) {
    		if (this.checkMode) {
    		    var record = grid.getStore().getAt(rowIndex);
    		    var sm = grid.getSelectionModel();
				var cm = grid.getColumnModel();
    		    var c = cm.getColumnById(cm.getColumnId(columnIndex));
    		    if (c.isCheckbox) {
    		    	if (sm.isSelected(rowIndex)) {
						if (grid.canAdd) {		
				    		var store = grid.getCheckStore();
			                var idx = store.find(grid.checkField, record.get(grid.getStore().reader.meta.idProperty));
			                if (idx < 0) {
				                var rt = store.recordType;
				                var r = new rt(grid.newRecord);		
				                r.set(grid.checkField, record.get(grid.getStore().reader.meta.idProperty));
				                store.insert(0, r);	
				                store.save();			                	
			                }
						}    		    		
    		    	}
    		    	else {
						if (grid.canDel) {
							var store = grid.getCheckStore();
							var rg = store.getRange();
				  			var idx = store.findExact(grid.checkField, record.get(grid.getStore().reader.meta.idProperty));
							if (idx >= 0) {
					    		store.remove(store.getAt(idx));
					    		store.save();							
							}								
						}    		    		    		    		
    		    	}
    		    }
    		}
    	}
    	this.getRowEditor = function() {
    		var lgrid = Ext.getCmp(config.id);
    		return lgrid.initialConfig.plugins[lgrid.rowEditorPluginIdx]; 
    	}
    	this.updateUI = function() {
    		var btn = Ext.getCmp(config.id + 'DelButton'); 
    		var grid = Ext.getCmp(config.id);
    		if (grid && btn) {
    			btn.setDisabled(!grid.getSelectionModel().hasSelection() || !grid.canDel || (typeof(grid.checkDel) == 'function' && !grid.checkDel()));
    		} 
    		if (config.updateUI) {
    			config.updateUI();
    		}
    	};
    	config.selModel.addListener('selectionchange', function(sm) {
    		this.updateUI();
    	}, this);	    
    	config.store.addListener('save', function(store, batch, data) {
    	}); 
    	config.store.addListener('load', function(store, records) {
    		if (this.filter) {
    			this.setFilter(this.filter.field, this.filter.value, this.filter.checkField, this.filter.checkValue, this.filter.anyMatch, this.filter.caseSensitive, this.filter.exactMatch);
    		}
    		else if (this.filterBy) {
    			this.setFilterBy(this.filterBy.fx, this.filterBy.checkFx, this.filterBy.scope);    			
    		}
    		this.updateUI();
    	}, this);     	
		Ext.ux.SimpleEditingGridPanel.superclass.constructor.call(this, config);
	},
	getCheckStore: function() {
		return this.checkStore;
	},
	setFilter: function(field, value, checkField, checkValue, anyMatch, caseSensitive, exactMatch) {
		if (typeof(field) != 'undefined'){
			//console.log('field: ' + field + ', value: ' + value + ', checkField: ' + checkField + ', checkValue: ' + checkValue + ', anyMatch: ' + anyMatch + ', caseSensitive: ' + caseSensitive + ', exactMatch: ' + exactMatch);
			if (this.getStore()) {
				this.getStore().filter(field, value, anyMatch, caseSensitive, exactMatch);
				this.filter = {
						field: field,
						value: value,
						checkField: checkField,
						checkValue: checkValue,
						anyMatch: anyMatch,
						caseSensitive: caseSensitive,
						exactMatch: exactMatch
				};
				this.filterBy = false;				
			}
		}		
		if (this.checkMode && typeof(checkField) != 'undefined') {	
			this.getCheckStore().filter(checkField, checkValue, anyMatch, caseSensitive, exactMatch);
		}
    	if (this.getView().mainBody) {
    		this.getView().refresh();     		
    	}
	},
	setFilterBy: function(fx, checkFx, scope) {
		if (typeof(fx) == 'function') {			
			this.getStore().filterBy(fx, scope);
			this.filterBy = {
					fx: fx,
					checkFx: checkFx,
					scope: scope
			}
			this.filter = false;
		}		
		if (this.checkMode && typeof(checkFx) == 'function') {	
			this.getCheckStore().filterBy(checkFx, scope);
		}
    	if (this.getView().mainBody) {
    		this.getView().refresh();     		
    	}
	},	
	clearFilter: function(suppressEvent) {
		if (this.checkMode) {				
			this.getCheckStore().clearFilter(suppressEvent);
		}
		this.getStore().clearFilter(suppressEvent);
    	if (this.getView().mainBody) {
    		this.getView().refresh();
    	} 
    	this.filter = false;
    	this.filterBy = false;
	}
});
Ext.reg('simpleeditinggridpanel', Ext.ux.SimpleEditingGridPanel);

function stdAjaxFailure(res, opt) {
	Ext.Msg.alert("Errore: transazione fallita", res.status + "-" + statusText + "<br>" + responseText);                                          
} 

function GridViewRefresh(gridId) {
	var grid = Ext.getCmp(gridId);
	if (grid && grid.getView().mainBody)
		grid.getView().refresh(); 		
}

function InputDel(campo) {
	if (campo.value.search(v[campo.name])== 0 ) {
		campo.value= '';
	}	
}

function InputFill(campo) {
	if (campo.value=='') {
		campo.value= v[campo.name];
	}	
}

function check_contatti(theForm) {		
	if (theForm.nome.value == "") {
    	alert("Per favore inserire il proprio nome, grazie.");
    	theForm.nome.focus();
    	return (false);
		}
	if (theForm.cognome.value == "") {
    	alert("Per favore inserire il proprio cognome, grazie.");
    	theForm.cognome.focus();
    	return (false);
		}	
	if (theForm.mittente.value == "") {
    	alert("Per favore inserire il proprio indirizzo Email, grazie.");
    	theForm.mittente.focus();
    	return (false);
	}
	if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/.test(theForm.mittente.value))) {
		alert("Indirizzo E-Mail non valido, si prega di verificarlo.\nGrazie.");
		theForm.mittente.focus();
		return (false);
		}	
	if (theForm.testo.value == "") {
    	alert("Per favore inserire il testo del messaggio, grazie.");
    	theForm.testo.focus();
    	return (false);
		}
	}

// Funzione per controllare l'invio della pagina

function ControlloInvio(theForm) {
	if (theForm.mail.value == "" || theForm.mail.value == "email*") {
    	alert("Per favore inserire la mail del destinatario, grazie.");
    	theForm.mail.focus();
    	return (false);
	}
	if (theForm.mittente.value == "" || theForm.mittente.value == "mittente*") {
    	alert("Per favore inserire il nome del mittente, grazie.");
    	theForm.mittente.focus();
    	return (false);
	}

}

// Funzione per controllare il numero di caratteri nel testo della mail

function CheckChars1(obj) {
  l_max = 250;
  l = obj.value.length;
  obj.form.total_chars1.value = l;
  if (l <= l_max) {
    return true;
  } else {
    window.alert('Attenzione: il testo supera i '+l_max+' caratteri consentiti');
    obj.value=obj.value.substring(0,l_max);
    obj.form.total_chars1.value = l_max;
    return false;
  }
}

function CheckChars2(obj) {
  l_max = 3000;
  l = obj.value.length;
  document.form2.total_chars2.value = l;
  if (l <= l_max) {
    return true;
  } else {
    window.alert('Attenzione: il testo supera i '+l_max+' caratteri consentiti');
    obj.value=obj.value.substring(0,l_max);
    document.form2.total_chars2.value = l_max;
    return false;
  }
}

function CheckChars3(obj) {
  l_max = 400;
  l = obj.value.length;
  document.form2.total_chars2.value = l;
  if (l <= l_max) {
    return true;
  } else {
    window.alert('Attenzione: il testo supera i '+l_max+' caratteri consentiti');
    obj.value=obj.value.substring(0,l_max);
    document.form2.total_chars2.value = l_max;
    return false;
  }
}

function CheckChars4(obj) {
  l_max = 1000;
  l = obj.value.length;
  document.form2.total_chars2.value = l;
  if (l <= l_max) {
    return true;
  } else {
    window.alert('Attenzione: il testo supera i '+l_max+' caratteri consentiti');
    obj.value=obj.value.substring(0,l_max);
    document.form2.total_chars2.value = l_max;
    return false;
  }
}

// funzioni per generare i pdf 

function PopUp(page,w,h,t,s,m) 
	{
	popwidth = w;
	popheight = h;
    if (!t) {t = 'no'};
	if (!s) {s = 'no'};
	if (!m) {m = 'no'};
	OpenWin = this.open(page, "prn", "toolbar=" + t + ", menubar=" + m +", location=no, scrollbars=" + s + ", resizable=no, width="+popwidth+", height="+popheight+", left=" + Math.floor((screen.width - popwidth) / 2) + ", top=" + Math.floor((screen.height - popheight) / 2));
}

function URLEncode(s)
{
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var plaintext = s;
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '" 
                        + ch 
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
		} // for

	
	return encoded;
};

function URLDecode(s)
{
   // Replace + with ' '
   // Replace %xx with equivalent character
   // Put [ERROR] in output if %xx is invalid.
   var HEXCHARS = "0123456789ABCDEFabcdef"; 
   var encoded = s;
   var plaintext = "";
   var i = 0;
   while (i < encoded.length) {
       var ch = encoded.charAt(i);
	   if (ch == "+") {
	       plaintext += " ";
		   i++;
	   } else if (ch == "%") {
			if (i < (encoded.length-2) 
					&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 
					&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				alert( 'Bad escape combination near ...' + encoded.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
		   plaintext += ch;
		   i++;
		}
	} // while
   
   return plaintext;
};

function mysqldate(dt) {
	var ret = '';
	if (null != dt && dt != '') {
	  var mm = dt.getMonth()+1;
	  var dd = dt.getDate();
	  var yyyy = dt.getFullYear();
	  ret = '' + yyyy + (mm < 10 ? '-0' : '-') + mm + (dd < 10 ? '-0' : '-') + dd;
	}	
	return ret;
}

function numSYStoIT(nStr)
{
    nStr += '';
    var ret = nStr.replace(/\./, ',');
    return ret;
}

function numITtoSYS(nStr)
{
    nStr += '';
    var ret = nStr.replace(/\./, '').replace(/,/, '.');
    return ret;
}

