﻿Ext.namespace('Vt.Search');


Vt.Search.store = new Ext.data.JsonStore({
	url: '/Home/GetResults',
	storeId: 'Vt.Search.store',
	root: 'items',
	fields: ['ProvinciaID', 'Nome', 'Comuni']
});

Vt.Search.pinTpl = new Ext.XTemplate('	<div style="">{Indirizzo} - {CAP}' +
'		{[values.Localita ? ", Loc. " + values.Localita: ""]}' +
'		{[values.Telefono ? ", Tel. " + values.Telefono: ""]}' +
'		{[values.Fax ? ", Tel. " + values.Fax: ""]}' +
'	</div>' +
'	<tpl if="this.exists(Email)">' +
'		<div><a href="mailto:{Email}">{Email}</a></div>' +
'	</tpl>' +
'	<tpl if="this.exists(Web)">' +
'		<div><a href="http://{Web}" target="_blank">{Web}</a></div>' +
'	</tpl>', {
	exists: function(o){
		return typeof o != 'undefined' && o != null && o != '';
	}
}).compile();

Vt.Search.MapPanel = Ext.extend(Ext.ux.BingMapPanel, {
	initComponent: function(){
	
		var defConfig = {
			plain: true,
			zoomLevel: 3,
			yaw: 180,
			pitch: 0,
			zoom: 0,
			gmapType: 'map',
			border: false
		};
		
		Ext.applyIf(this, defConfig);
		
		//		alert('mappanel');
		
		Vt.Search.MapPanel.superclass.initComponent.call(this);
		
		this.store.on('load', this.onStoreLoad, this);
	},
	onStoreLoad: function(store, records){
		if (records.length > 0) {
			Ext.fly('mapLegend').setStyle({
				display: 'block'
			});
			Ext.fly('newSearch').setStyle({
				display: 'block'
			});
			this.show();
			var bmap = this.getMap();
			bmap.DeleteAllShapeLayers();
			this.buildList(records, "Ambulanti", '05', Vt.Search.pinTpl)
			this.buildList(records, "Sagre", '03', Vt.Search.pinTpl)
			this.buildList(records, "Manifestazioni", '04', Vt.Search.pinTpl)
			this.buildList(records, "Botteghe", '02', Vt.Search.pinTpl)
			this.buildList(records, "Ristoranti", '01', Vt.Search.pinTpl)
		}
		else {
			Ext.fly('mapLegend').setStyle({
				display: 'none'
			});
			Ext.fly('newSearch').setStyle({
				display: 'none'
			});
			this.hide();
		}
	},
	buildList: function(records, itemsName, iconName, tpl){
		var items = new Array();
		var i;
		var j;
		var k;
		var item;
		for (i = 0; i < records.length; i++) {
			//		alert(records[i].data.Comuni.length);
			for (j = 0; j < records[i].data.Comuni.length; j++) {
				for (k = 0; k < records[i].data.Comuni[j][itemsName].length; k++) {
					item = records[i].data.Comuni[j][itemsName][k];
					if (item.Latitude !== 0 && item.Longitude !== 0) {
						items.push(item);
					}
				}
			}
		}
		//	alert(records.length);
		if (items.length > 0) {
			return this.displayMap(items, itemsName, iconName, tpl);
		}
		
	},
	displayMap: function(items, itemsName, iconName, tpl){
		var bmap = this.getMap();
		var point;
		var layer = this.findLayer(itemsName);
		if (layer) {
			bmap.DeleteShapeLayer(layer);
		}
		//		bmap.ClearInfoBoxStyles();
		
		layer = new VEShapeLayer();
		layer.SetTitle(itemsName);
		for (var i = 0; i < items.length; i++) {
			if (items[i].Latitude > 47 || items[i].Longitude > 15 ||
			items[i].Latitude < 41 ||
			items[i].Longitude < 9) {
				continue
			}
			point = new VELatLong(items[i].Latitude, items[i].Longitude);
			var pin = new VEShape(VEShapeType.Pushpin, point);
			pin.SetTitle(String.format('<div class="item-selector" ><a href="/{0}/Details/{1}">{2}</a></div>', itemsName, items[i].ID, items[i].Denominazione));
			pin.SetDescription(tpl.applyTemplate(items[i]));
			pin.SetCustomIcon('/Content/MapIcons/balls/' + iconName + '.png');
			layer.AddShape(pin);
		}
		//Specifying clustering
		//layer.SetClusteringConfiguration(VEClusteringType.Grid);
		bmap.AddShapeLayer(layer);
		bmap.SetMapView(layer.GetBoundingRectangle());
		this.show();
	}
});

Ext.reg('mappanel', Vt.Search.MapPanel);


Vt.Search.ResultList = Ext.extend(Ext.DataView, {

	id: 'result-list',
	store: Vt.Search.store,
	tpl: Vt.Templates.ResultList,
	loadingText: 'Loading',
			
			contentContainerID: 'content-container',
	localConfig: {
		itemName: 'ItemName',
		itemsName: 'ItemsName',
		resultViewerID: 'result-list'
	},
	
	initComponent: function(){
		Ext.applyIf(this, {
			autoHeight: true,
			singleSelect: true,
			overClass: 'x-view-over',
			itemSelector: 'div.item-selector',
			emptyText: 'Nessun risultato'
		
		});
		Ext.apply(this, {});
		Vt.Search.ResultList.superclass.initComponent.call(this);
		this.on('selectionchange', function(dv, selections){
			//			alert('selectionchange');
			this.onSelectionChange(dv, selections);
		});
	},
	onSelectionChange: function(dv, selections){
		Ext.getCmp(this.contentContainerID).ShowDetails(parseInt(selections[0].id.split('-')[1]));
	}
});

Ext.reg('Vt.Search.ResultList', Vt.Search.ResultList);

Vt.Search.storeProvince = {
	xtype: 'jsonstore',
	//	autoDestroy: true,
	url: '/Info/GetProvince',
	autoLoad: true,
	root: 'items',
	idProperty: 'ProvinciaID',
	fields: ['ProvinciaID', 'Nome']
};

Vt.Search.storeComuni = new Ext.data.JsonStore({
	xtype: 'jsonstore',
	//	autoLoad: true,
	url: '/Info/GetComuni',
	root: 'items',
	idProperty: 'ID',
	fields: ['ID', 'Nome', 'ProvinciaID']
});
Vt.Search.storeComuni.load();

Vt.Search.provinceTpl = new Ext.XTemplate('<table class="btn-table" cellspacing="1" cellpadding="1" border="1">' +
'<tr>' +
'<tpl for=".">' +
'<td><div style="width:105px;"><div id="item-{ProvinciaID}" class="provincia-selector btn-table-image" ><img src="/Content/Images/Items/{ProvinciaID}.gif" /><div class="btn-table-caption">{Nome}</div></div></div></td>' +
'{[xindex === 5 ? "</tr><tr>" : ""]}' +
'</tpl>' +
'</tr>' +
'</table>').compile();


Vt.Search.BtnPanel = Ext.extend(Ext.DataView, {

	id: 'btn-panel',
	readAdditionalParams: function(form, params){
		return params;
	},
	
	initComponent: function(){
		Ext.applyIf(this, {
			store: Vt.Search.storeProvince,
			tpl: Vt.Search.provinceTpl,
			width: 550,
			autoHeight: true,
			singleSelect: true,
			overClass: 'x-view-over',
			itemSelector: 'div.provincia-selector',
			emptyText: 'Nessun elemento'
		});
		Ext.apply(this, {});
		Vt.Search.BtnPanel.superclass.initComponent.call(this);
		
		this.on('selectionchange', function(dv, selections){
			//						alert('provinciaHandler');
			this.provinciaHandler(dv.getSelectedRecords()[0].data.ProvinciaID);
		});
	},
	provinciaHandler: function(provinciaID){
		var params = Vt.Search.FnGetParameters();
		params.provinciaID = provinciaID;
		Ext.StoreMgr.get('Vt.Search.store').load({
			params: params
		});
	}
});

Ext.reg('Vt.Search.BtnPanel', Vt.Search.BtnPanel);

Vt.Search.SearchObjectsFnOnChecked = function(cb, checked){
	//	alert(checked);
};

Vt.Search.FnGetParameters = function(forGet){
	var params = {};
	params.showRistoranti = Ext.getCmp('cb-ristoranti').getValue();
	params.showBotteghe = Ext.getCmp('cb-botteghe').getValue();
	params.showSagre = Ext.getCmp('cb-sagre').getValue();
	params.showManifestazioni = Ext.getCmp('cb-manifestazioni').getValue();
	params.showAmbulanti = Ext.getCmp('cb-ambulanti').getValue();
	params.showStorici = Ext.getCmp('cb-storici').getValue();
	//	alert(showRistoranti);
	var provinciaID = Ext.getCmp('field-provincia').getValue();
	if (provinciaID) {
		params.provinciaID = provinciaID;
	}
	var comune = Ext.getCmp('comune').getValue();
	if (comune) {
		params.comune = comune;
	}
	var denominazione = Ext.getCmp('denominazione').getValue();
	if (denominazione) {
		params.denominazione = denominazione;
	}
	//	var startDate = Ext.getCmp('startDate').getRawValue();
	var startDate = Ext.getCmp('startDate').getValue();
	if (startDate) {
		if (forGet) {
			params.startDate = startDate.format('m/d/Y');
		}
		else {
			params.startDate = startDate.format('d/m/Y');
	//		alert(params.startDate);
		}
	}
	var endDate = Ext.getCmp('endDate').getValue();
	if (endDate) {
		if (forGet) {
			params.endDate = endDate.format('m/d/Y');
		}
		else {
			params.endDate = endDate.format('d/m/Y');
		}
	}
	return params;
};

Vt.Search.SearchObjects = new Ext.form.FieldSet({
	title: 'Tipologia',
	collapsible: true,
	animCollapse: true,
	autoHeight: true,
	autoWidth: true,
	layout: 'column',
	items: [{
		xtype: 'panel',
		columnWidth: 0.5,
		defaultType: 'checkbox',
		items: [{
			id: 'cb-ristoranti',
			boxLabel: 'Ristoranti',
			checked: false,
			listeners: {
				check: {
					fn: Vt.Search.SearchObjectsFnOnChecked
				}
			}
		}, {
			id: 'cb-botteghe',
			boxLabel: 'Botteghe',
			checked: false,
			listeners: {
				check: {
					fn: Vt.Search.SearchObjectsFnOnChecked
				}
			}
		}]
	}, {
		xtype: 'panel',
		columnWidth: 0.5,
		defaultType: 'checkbox',
		items: [{
			id: 'cb-sagre',
			boxLabel: 'Sagre e Fiere',
			checked: false,
			listeners: {
				check: {
					fn: Vt.Search.SearchObjectsFnOnChecked
				}
			}
		}, {
			id: 'cb-manifestazioni',
			boxLabel: 'Manifestazioni fieristiche',
			checked: false,
			listeners: {
				check: {
					fn: Vt.Search.SearchObjectsFnOnChecked
				}
			}
		}, {
			id: 'cb-ambulanti',
			boxLabel: 'Mercati ambulanti',
			checked: false,
			listeners: {
				check: {
					fn: Vt.Search.SearchObjectsFnOnChecked
				}
			}
		}, {
			id: 'cb-storici',
			boxLabel: 'Commercio storico',
			checked: false,
			listeners: {
				check: {
					fn: Vt.Search.SearchObjectsFnOnChecked
				}
			}
		}]
	}]
});

Vt.Search.Luogo = new Ext.form.FieldSet({
	title: 'Luogo',
	collapsible: true,
	animCollapse: true,
	autoHeight: true,
	autoWidth: true,
	items: [{
		xtype: 'combo',
		id: 'field-provincia',
		fieldLabel: 'Provincia',
		store: new Ext.data.SimpleStore({
			fields: ['provinciaID', 'provinciaNome', 'provinciaIcon'],
			data: [['AR', 'Arezzo', 'ux-provincia-icon-ar'], ['FI', 'Firenze', 'ux-provincia-icon-fi'], ['GR', 'Grosseto', 'ux-provincia-icon-gr'], ['LI', 'Livorno', 'ux-provincia-icon-li'], ['LU', 'Lucca', 'ux-provincia-icon-lu'], ['MS', 'Massa e Carrara', 'ux-provincia-icon-ms'], ['PI', 'Pisa', 'ux-provincia-icon-pi'], ['PT', 'Pistoia', 'ux-provincia-icon-pt'], ['PO', 'Prato', 'ux-provincia-icon-po'], ['SI', 'Siena', 'ux-provincia-icon-si']]
		}),
		plugins: new Ext.ux.plugins.IconCombo(),
		valueField: 'provinciaID',
		displayField: 'provinciaNome',
		iconClsField: 'provinciaIcon',
		triggerAction: 'all',
		mode: 'local',
		listeners: {
			change: {
				fn: function(combo, value){
					//														alert(combo.getValue());
					var val = combo.getValue();
					if (val) {
						var comboComune = Ext.getCmp('comune');
						comboComune.clearValue();
						comboComune.store.filter('ProvinciaID', val);
					}
					else {
						//														alert('else');
						/*								comboComune.store.clearFilter();
						 comboComune.clearValue();
						 comboComune.lastQuery = '';
						 comboComune.doQuery();*/
					}
				}
			}
		}
	}, {
		xtype: 'combo',
		id: 'comune',
		fieldLabel: 'Comune',
		typeAhead: true,
		mode: 'remote',
		selectOnFocus: true,
		allowBlank: true,
		forceSelection: true,
		displayField: 'Nome',
		valueField: 'Nome',
		hiddenName: 'Nome',
		loadingText: 'Caricamento...',
		minChars: 1,
		triggerAction: 'all',
		lastQuery: '',
		store: Vt.Search.storeComuni
	}, {
		xtype: 'textfield',
		id: 'localita',
		fieldLabel: 'Località',
		width: 300
	}]
});

Vt.Search.DateRange = new Ext.form.FieldSet({
	title: 'Data',
	collapsible: true,
	animCollapse: true,
	autoHeight: true,
	autoWidth: true,
	layout: 'column',
	items: [{
		xtype: 'panel',
		columnWidth: 0.5,
		layout: 'form',
		items: [{
			xtype: 'datefield',
			id: 'startDate',
			fieldLabel: 'Inizio',
			value: new Date()
		}]
	}, {
		xtype: 'panel',
		columnWidth: 0.5,
		layout: 'form',
		items: [{
			xtype: 'datefield',
			id: 'endDate',
			fieldLabel: 'Fine'
		}]
	}]
});

Vt.Search.Generale = new Ext.form.FieldSet({
	title: 'Generale',
	collapsible: true,
	animCollapse: true,
	autoHeight: true,
	autoWidth: true,
	items: [{
		xtype: 'textfield',
		id: 'denominazione',
		fieldLabel: 'Denominazione'
	}]
});

Vt.Search.SearchForm = Ext.extend(Ext.FormPanel, {
	id: 'btn-search',
	title: 'Ricerca',
	border: true,
	frame: true,
	collapsible: true,
	bodyStyle: 'padding:15px',
	width: 550,
	defaultType: 'textfield',
	defaults: {
		// applied to each contained item
		width: 260,
		msgTarget: 'side'
	},
	localConfig: {
		itemName: 'ItemName',
		itemsName: 'ItemsName',
		resultViewerID: 'result-list'
	},
	additionalItems: [],
	readAdditionalParams: function(form, params){
		return params;
	},
	
	initComponent: function(){
		Ext.applyIf(this, {
			items: [Vt.Search.SearchObjects, Vt.Search.Luogo, Vt.Search.DateRange, Vt.Search.Generale].concat(this.additionalItems)
		
		});
		Ext.apply(this, {
			buttons: [{
				xtype: 'linkbutton',
				id: 'btn-getpdf',
				text: 'Genera catalogo PDF',
				href: '/Home/GetPdf',
				target: '_blank',
				//				scope: this,
				handler: this.pdfHandler
			}, {
				id: 'btn-search',
				text: 'Trova',
				scope: this,
				handler: this.showHandler
			}],
			// config options applicable to container when layout='form':
			hideLabels: false,
			labelAlign: 'left', // or 'right' or 'top'
			labelSeparator: ':', // takes precedence over layoutConfig value
			labelWidth: 90, // defaults to 100
			labelPad: 8 // defaults to 5, must specify labelWidth to be honored
		});
		Vt.Search.SearchForm.superclass.initComponent.call(this);
	},
	showHandler: function(b, e){
		//				alert(that);
		var params = Vt.Search.FnGetParameters();
		
		Ext.StoreMgr.get('Vt.Search.store').load({
			params: params
		});
	},
	pdfHandler: function(b, e){
		var params = Vt.Search.FnGetParameters(true);
		//		alert(params);
		b.setParams(params);
	}
});

Ext.reg('Vt.Search.SearchForm', Vt.Search.SearchForm);
