/* 
 Tolomeo is a developing framework for visualization, editing,  
 geoprocessing and decisional support application based on cartography.
 
 Tolomeo Copyright 2011 Comune di Prato;
 
 This file is part of Tolomeo.
 
 Tolomeo is free software; you can redistribute it and/or modify
 it under the terms of the GNU Lesser General Public License 
 as published by the Free Software Foundation; either version 3 of the License, 
 or (at your option) any later version.
 
 Tolomeo is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
 
 You should have received a copy of the GNU Lesser General Public License along with Tolomeo; 
 if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110­1301  USA
 
 Developers Information:
 
 Tolomeo is developed by Comune di Prato
 
 Alessandro Radaelli
 Federico Nieri
 Mattia Gennari
 
 sit@comune.prato.it 
 
 
 Versione in Italiano LGPL
 
 Tolomeo č un framework per lo sviluppo di applicazioni per
 visualizzazione, editing, geoprocessing e supporto alla decisione basate su cartografia.
 
 Tolomeo Copyright 2011 Comune di Prato;
 
 Questo file fa parte di Tolomeo.
 
 Tolomeo č un software libero; č possibile redistribuirlo e / o 
 modificarlo sotto i termini della GNU Lesser General Public License, 
 come pubblicato dalla Free Software Foundation, sia la versione 3 della licenza o (a propria scelta) una versione successiva.
  
 Tolomeo č distribuito nella speranza che possa essere utile,
 ma SENZA ALCUNA GARANZIA, senza neppure la garanzia implicita di COMMERCIABILITĄ o
 IDONEITĄ PER UN PARTICOLARE SCOPO. Vedere la GNU Lesser General Public License per ulteriori dettagli.
 
 Si dovrebbe avere ricevuto una copia della GNU Lesser General Public insieme a Tolomeo, in caso contrario, 
 si scriva alla Free Software  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110­1301 USA
   
 
 Informazioni Sviluppatori:
 
 Tolomeo č sviluppato dal Comune di Prato
 
 Alessandro Radaelli
 Federico Nieri
 Mattia Gennari
 
 sit@comune.prato.it
*/

Ext.namespace("TolomeoExt");

/**
 * Class: TolomeoExt.ToloPanelStradario
 * 
 * Inherits from: - <Ext.Panel>
 * 
 */
TolomeoExt.ToloPanelStradario = Ext.extend(Ext.Panel, {

	/**
	 * Property: paramsJS {JSONObject}
	 * 
	 */
	paramsJS : null,

	/**
	 * Property: TOLOMEOServer {String}
	 * 
	 */
	TOLOMEOServer : null,

	/**
	 * Property: TOLOMEOContext {String}
	 * 
	 */
	TOLOMEOContext : null,

	/**
	 * Property: suggestWithGeom {Boolean}
	 * 
	 */
	suggestWithGeom : false,

	/**
	 * Property: codTPNStrade {Number}
	 * 
	 */
	codTPNStrade : -510,

	/**
	 * Property: idRicercaStrade {Number}
	 * 
	 */
	idRicercaStrade : 1,

	/**
	 * Property: codTPNCivici {Number}
	 * 
	 */
	codTPNCivici : -610,

	/**
	 * Property: idRicercaCivici {Number}
	 * 
	 */
	idRicercaCivici : 1,

	/**
	 * Property: toolbar {TolomeoExt.ToloButtonPanelExt}
	 * 
	 */
	toolbar : null,

	/**
	 * Property: mapPanel {}
	 * 
	 */
	mapPanel : null,

	/**
	 * Property: toolsPanel {}
	 * 
	 */
	toolsPanel : null,

	legendaPanelOpt : null,

	legendaPanel : null,

	/**
	 * Property: formPanelSearch {}
	 * 
	 */
	formPanelSearch : null,

	/**
	 * Property: gridView {}
	 * 
	 */
	gridView : null,

	/**
	 * Property: api {}
	 * 
	 */
	api : null,

	/**
	 * Property: fldVia {}
	 * 
	 */
	fldVia : null,

	/**
	 * Property: fldCivico {}
	 * 
	 */
	fldCivico : null,

	/**
	 * Property: listPanel {}
	 * 
	 */
	listPanel : null,

	/**
	 * Property: btnCerca {}
	 * 
	 */
	btnCerca : null,

	/**
	 * Property: viewerConfig {} Configurazione che sarą utilizzata per il
	 * viewer.
	 * 
	 */
	viewerConfig : null,
	
	ofcPanel: null,

	/**
	 * Method: initComponent Metodo relativo alla gestione Ext.
	 * 
	 */
	initComponent : function() {

		// Applico i default
		TolomeoExt.Vars.ApplyIfDefaults(this);

		this.layout = 'border';
		this.monitorResize = true;

		//Toolbar
		this.toolbar = new TolomeoExt.ToloButtonPanelExt({
			withPanArrows   : true,
			withLegenda     : false,
			withQuery       : false,
			withSeleziona   : false,
			withAutoIdentify: false,
			paramsJS        : this.paramsJS,
			defaults        : { scale: 'medium' },
			iconBasePath    : this.TOLOMEOServer + '/mycommon/img/icone24-default/'
		});
		this.tbar = this.toolbar;
		
		TolomeoExt.ToloPanelStradario.superclass.initComponent.call(this);

		var cfg = Ext.apply({}, this.viewerConfig);

		//Legenda
		this.legendaPanelOpt = {
			border        : false,
			layout        : 'anchor',
			paramsJS      : this.paramsJS,
			TOLOMEOServer : this.TOLOMEOServer,
			TOLOMEOContext: this.TOLOMEOContext,
			xtype         : 'tx_toloMenuTOCPanelExt'
		};
		this.legendaPanel = new TolomeoExt.ToloMenuTOCPanelExt(this.legendaPanelOpt);
		
		this.ofcPanel = new Ext.Panel ({
			layout    : 'anchor',
			border    : false,
			autoHeight: true,
			width     : 82,
			bodyStyle : 'background-color: white;',
			style     : 'background-color: white; z-index:1; top:auto; left:auto; right: 10px; top: 10px',
			layoutConfig: {
				align: 'stretch'
			},
			items     : [{
				xtype: 'box',
				autoEl: {
					tag: 'img',
					id: 'icona',
					src: this.TOLOMEOServer + '/img/legenda/icona_mappa.png'
				},
				margins: {top:0, right:0, bottom:0, left:0}
			}, this.legendaPanel]
		});
		
		this.legendaPanel.on('layerCheckedChange', this.changeIcon, this);
		
		//Viewer
		this.mapPanel = new TolomeoExt.ToloViewerOLPanel(Ext.apply(cfg, {
			region   : 'center',
			xtype    : "tx_toloviewerOLPanel",
			//inizializzazione dimensioni, poi vengono ricalcolate dal viewer
			height   : 50,
			width    : 50,
			layout   : "fit",
			paramsJS : this.paramsJS
		}));

		this.mapPanel.add(this.ofcPanel);
		
		var proxy = TolomeoExt.ToloCrossAjaxUtil.getProxy(null, this.TOLOMEOServer + this.TOLOMEOContext + '/AjaxSuggestServlet');
		var ds = new Ext.data.JsonStore({
			proxy      : proxy,
			baseParams : {
				format   : "ext",
				idCampo  : 0,
				codTPN   : this.codTPNStrade,
				idRicerca: this.idRicercaStrade,
				withGeom : this.suggestWithGeom
			}
		});

		//Pannello ricerca
		this.fldVia = new Ext.form.ComboBox({
			monitorResize : true,
			fieldLabel    : 'Via',
			anchor        : '90%',
			name          : 'campoRicerca0',
			forceSelection: false,
			allowBlank    : false,
			store         : ds,
			displayField  : 'description',
			valueField    : 'key',
			hiddenName    : 'key',
			queryParam    : 'q',
			typeAhead     : false,
			loadingText   : 'Ricerca...',
			minChars      : 3,
			hideTrigger   : true
		});

		this.fldCivico = new Ext.form.TextField({
			monitorResize: true,
			maxLength    : 12,
			fieldLabel   : 'Civico',
			anchor       : '90%',
			name         : 'campoRicerca1',
			allowBlank   : true,
			maskRe       : /\d/
		});

		this.btnCerca = new Ext.Button({
			monitorResize: true,
			text         : 'Cerca',
			formBind     : true,
			type         : 'submit',
			handler      : this.cerca,
			scope        : this
		});

		var fs = new Ext.form.FieldSet({
			monitorResize: true,
			anchor       : '-3',
			autoWidth    : true,
			autoHeight   : true,
			border       : false,
			defaultType  : 'textfield',
			items        : [this.fldVia, this.fldCivico],
			buttons      : [this.btnCerca, {
				text    : "Pulisci",
				handler : function() {
					Ext.getCmp('formPanelSearch').getForm().reset();
					Ext.getCmp('listPanel').hide();
				}
			}]
		});

		var store = new Ext.data.ArrayStore({
			autoDestroy : true,
			storeId     : 'store',
			idIndex     : 0,
			fields      : ['id', 'description']
		});

		this.gridResults = new Ext.ListView({
			monitorResize: true,
			autoWidth    : true,
			height       : 300,
			autoScroll   : true,
			store        : store,
			columns      : [{
				header   : 'Seleziona l\'oggetto desiderato',
				dataIndex: 'description',
				sortable : true,
				tpl      : '<a href="#" class="x-list-body" style="padding:0;margin:0;">{description}</a>'
			}]
		});

		this.listPanel = new Ext.Panel({
			id        : 'listPanel',
			title     : 'Lista risultati',
			frame     : false,
			hidden    : true,
			layout    : 'fit',
			autoWidth : true,
			autoScroll: true,
			height    : 300,
			items     : [this.gridResults]
		});

		this.gridResults.on('mouseenter', this.overIn, this);
		this.gridResults.on('mouseleave', this.overOut, this);
		this.gridResults.on('click', this.click, this);

		this.formPanelSearch = new Ext.FormPanel({
			id           : 'formPanelSearch',
			title        : 'Cerca un indirizzo',
			region       : 'east',
			bodyStyle    : 'padding: 5px',
			width        : 300,
			minSize      : 250,
			maxSize      : 300,
			split        : true,
			collapsed    : false,
			collapsible  : true,
			border       : true,
			labelWidth   : 40,
			defaultType  : 'textfield',
			monitorValid : true,
			monitorResize: true,
			items : [fs, this.listPanel]
		});

		this.formPanelSearch.on('clientValidation', function(form, valid) {
			this.btnCerca.setDisabled(!valid);
		}, this);

		this.add(this.mapPanel);
		this.add(this.formPanelSearch);
		this.doLayout();
	},

	changeIcon: function(layer) {		
		var isAtLeastOneChecked = layer.checked;
		if(!isAtLeastOneChecked){
			for (var i=0; i<layer.category.layers.length; i++) {
				if(layer.category.layers[i].checked){
					isAtLeastOneChecked = true;
					break;
				}
			}
		}
		Ext.fly('icona').set({src:this.TOLOMEOServer + (isAtLeastOneChecked?'/img/legenda/icona_ortofoto.png':'/img/legenda/icona_mappa.png')});
	},
	
	/**
	 * Method: afterRender Metodo privato invocato dopo che il pannello č stato
	 * renderizzato.
	 * 
	 */
	afterRender : function() {

		TolomeoExt.ToloPanelStradario.superclass.afterRender.apply(this,
				arguments);

		if (this.api == null) {
			this.api = new TolomeoExt.ToloMapAPIExt({
				paramsJS    : this.paramsJS,
				viewer      : this.mapPanel,
				buttonsPanel: this.toolbar,
				TOCPanel    : this.legendaPanel,
				titoloMappa : 'Stradario di Prato'
			});
		}

		this.loadMask = new Ext.LoadMask(this.id, {
					msg : "Attendere prego..."
				});
		this.loadMask.enable();
	},

	/**
	 * Method: cerca
	 * 
	 */
	cerca: function cerca() {

		this.loadMask.show();

		if (!this.btnCerca.disabled) {
			this.api.clearSelected(false);
			this.api.clearHighLigthed(false);

			var fparams = this.formPanelSearch.getForm().getValues();

			if ((this.fldCivico.getValue() != null) && (this.fldCivico.getValue() != "")) {
				// ricerca via e civico
				fparams.campoRicerca0 = this.fldVia.getValue();
				fparams.campoRicerca1 = this.fldCivico.getValue();
				fparams.format        = "ext";
				fparams.codTPN        = this.codTPNCivici;
				fparams.idCampo       = 0;
				if (this.fldVia.getValue() == this.fldVia.getRawValue())
					fparams.idRicerca = 2; //per descrizione
				else
					fparams.idRicerca = 3; //per id
			} else {
				// ricerca solo via
				fparams.campoRicerca0 = this.fldVia.getValue();
				fparams.format        = "ext";
				fparams.codTPN        = this.codTPNStrade;
				fparams.idCampo       = 0;
				if (this.fldVia.getValue() == this.fldVia.getRawValue()) {
					fparams.idRicerca = 4; //per descrizione
				} else {
					fparams.idRicerca = 3; //per id
				}
			}

			var submitOpt = {
				url    : this.TOLOMEOServer + this.TOLOMEOContext+ '/AjaxQueryServlet',
				method : 'POST',
				params : fparams,
				success: this.doOnQueryAjaxCallback,
				failure: this.doOnQueryAjaxFailure,
				scope  : this
			};

			new TolomeoExt.ToloCrossAjax().request(submitOpt);
		}
	},

	/**
	 * Method: doOnQueryAjaxFailure
	 * 
	 */
	doOnQueryAjaxFailure : function() {
		this.loadMask.hide();
		Ext.Msg.show({
			title  : 'Ricerca indirizzo',
			msg    : 'Errore durante la ricerca.',
			buttons: Ext.Msg.OK,
			icon   : Ext.MessageBox.ERROR
		});
	},

	/**
	 * Method: doOnQueryAjaxCallback
	 * 
	 * Parameters: results - {} results. store - {} store.
	 * 
	 */
	doOnQueryAjaxCallback : function(results, store) {

		this.loadMask.hide();

		if (store.getTotalCount() == 0) {
			Ext.MessageBox.alert('Ricerca indirizzo', 'Nessun risultato per la ricerca impostata.').getDialog().focus();
		} else if (store.getTotalCount() == 1) {
			this.listPanel.setVisible(false);

			var record = store.getAt(0).data;
			var geom = new JSGeometry(record.codTPN, record.key, record.description, record.geometry, record.boundingbox, record.SRID);
			this.found(geom);
		} else {
			var boundingBox = store.reader.meta.boundingBox;

			this.api.zoomToExtent(boundingBox);

			var titolo = 'Trovati ' + store.getTotalCount() + ' risultati per "' + this.fldVia.getRawValue();
			if (this.fldCivico.getValue() != "")
				titolo += ', ' + this.fldCivico.getValue() + '"';
			else
				titolo += '"';

			this.listPanel.setTitle(titolo);
			this.listPanel.setVisible(true);
			this.gridResults.bindStore(store);
		}
	},

	/**
	 * Method: click
	 * 
	 * Parameters: dv - {} dv. index - {} index. node - {} il nodo. e - {}
	 * l'evento.
	 */
	click : function(dv, index, node, e) {
		var record = dv.getRecord(node).data;
		var geom = new JSGeometry(record.codTPN, record.key, record.description, record.geometry, record.boundingbox, record.SRID);
		this.found(geom);
	},

	/**
	 * Method: found
	 * 
	 * Parameters: geom - {} la geometria.
	 */
	found : function(geom) {
		if (geom.geometry) {
			this.api.addSelected(geom);
			this.api.zoomToSelected(null,200);
			this.listPanel.hide();
		} else {
			Ext.Msg.alert('Ricerca indirizzo','L\'oggetto richiesto non &egrave; pozionato sulla cartografia.').getDialog().focus();
		}
	},

	/**
	 * Method: overIn
	 * 
	 * Parameters: dv - {} dv. index - {} index. node - {} il nodo. e - {}
	 * l'evento.
	 */
	overIn : function(dv, index, node, e) {
		var record = dv.getRecord(node).data;
		/** @type {JSGeometry} * */
		var geom = new JSGeometry(record.codTPN, record.key,record.description, record.geometry, record.boundingbox, record.SRID);
		if (geom.geometry) this.api.addHighlighted(geom);
	},

	/**
	 * Method: overOut
	 * 
	 * Parameters: dv - {} dv. index - {} index. node - {} il nodo. e - {}
	 * l'evento.
	 */
	overOut : function(dv, index, node, e) {
		this.api.clearHighLigthed();
	}
});

// /** api: xtype = gx_mappanel */
Ext.reg('tx_ToloPanelStradario', TolomeoExt.ToloPanelStradario);
