﻿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.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('field-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: true,
			listeners: {
				check: {
					fn: Vt.Search.SearchObjectsFnOnChecked
				}
			}
		}, {
			id: 'cb-manifestazioni',
			boxLabel: 'Manifestazioni fieristiche',
			checked: true,
			listeners: {
				check: {
					fn: Vt.Search.SearchObjectsFnOnChecked
				}
			}
		}, {
			id: 'cb-ambulanti',
			boxLabel: 'Mercati ambulanti',
			checked: true,
			listeners: {
				check: {
					fn: Vt.Search.SearchObjectsFnOnChecked
				}
			}
		}, {
			id: 'cb-storici',
			boxLabel: 'Commercio storico',
			checked: true,
			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: '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
			}, {
				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);

Ext.onReady(function () {
	Ext.QuickTips.init();
	var selectComuni = new Ext.Panel({
		renderTo: 'selectComuni',
		layout: 'form',
		title: 'Seleziona comune',
		border: true,
		frame: true,
		bodyStyle: 'padding:15px',
		width: 550,
		items: [{
			xtype: 'combo',
			id: 'field-provincia',
			editable: false,
			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']]
			}),
			valueField: 'provinciaID',
			displayField: 'provinciaNome',
			iconClsField: 'provinciaIcon',
			triggerAction: 'all',
			mode: 'local',
			listeners: {
				change: {
					fn: function (combo, value) {
						var val = Ext.getCmp('field-provincia').getValue();
						if (val) {
							var comboComune = Ext.getCmp('field-comune');
							comboComune.clearValue();
							comboComune.store.filter('ProvinciaID', val);
						}
						else {
						}
					}
				}
			}
		}, {
			xtype: 'combo',
			id: 'field-comune',
			fieldLabel: 'Comune',
			typeAhead: true,
			mode: 'remote',
			selectOnFocus: true,
			allowBlank: false,
			forceSelection: true,
			editable: false,
			displayField: 'Nome',
			valueField: 'Nome',
			hiddenName: 'Nome',
			loadingText: 'Caricamento...',
			minChars: 1,
			triggerAction: 'all',
			lastQuery: '',
			store: Vt.Search.storeComuni,
			listeners: {
				select: {
					fn: function () {
						var params = Vt.Search.FnGetParameters();

						Ext.StoreMgr.get('Vt.Search.store').load({
							params: params
						});
					}
				}
			}
		}]
	});
	var ricerca = new Vt.Search.SearchForm({
		renderTo: 'ricerca'
	});

	var resultMap = new Vt.Search.MapPanel({
		renderTo: 'resultMap',
		store: Vt.Search.store,
		hidden: true,
		width: 500,
		height: 300,
		zoomLevel: 7,
		bodyStyle: {
			'margin-left': 'auto',
			'margin-right': 'auto',
			'text-align': 'center'
		},
		gmapType: 'map',
		mapConfOpts: ['enableScrollWheelZoom', 'enableDoubleClickZoom', 'enableDragging'],
		mapControls: ['GSmallMapControl', 'GMapTypeControl', 'NonExistantControl'],
		setCenter: {
			lat: 43.288075256347656,
			lng: 11.12460708618164
		}
	});

	var resulList = new Vt.Search.ResultList({
		renderTo: 'resultList'
	});
});

