﻿/**
 * @class Ext.ux.LinkButton
 * @extends Ext.Button
 * A Button which encapsulates an &lt;a> element to enable navigation, or downloading of files.
 * @constructor
 * Creates a new LinkButton
 * @author: extjs user animal
 */ 
Ext.ux.LinkButton = Ext.extend(Ext.Button, {
    template: new Ext.Template(
        '<table cellspacing="0" class="x-btn {3}"><tbody class="{4}">',
            '<tr>',
                '<td class="x-btn-tl"><i> </i></td>',
                '<td class="x-btn-tc"></td>',
                '<td class="x-btn-tr"><i> </i></td>',
            '</tr>',
            '<tr>',
                '<td class="x-btn-ml"><i> </i></td>',
                '<td class="x-btn-mc">',
                    '<em class="{5}" unselectable="on">',
                        '<a href="{6}" style="display:block" target="{7}" class="x-btn-text {2}" style="text-decoration: none; color: black; padding-left: 3px; padding-right: 3px;">{0}</a>',
                    '</em>',
                '</td>',
                '<td class="x-btn-mr"><i> </i></td>',
            '</tr>',
            '<tr>',
                '<td class="x-btn-bl"><i> </i></td>',
                '<td class="x-btn-bc"></td>',
                '<td class="x-btn-br"><i> </i></td>',
            '</tr>',
        '</tbody></table>'
    ).compile(),

    buttonSelector : 'a:first',

    /**
     * @cfg String href
     * The URL to create a link for.
     */
    /**
     * @cfg String target
     * The target for the &lt;a> element.
     */
    /**
     * @cfg Object
     * A set of parameters which are always passed to the URL specified in the href
     */
    baseParams: {},

//  private
    params: {},

    getTemplateArgs: function() {
        return Ext.Button.prototype.getTemplateArgs.apply(this).concat([this.getHref(), this.target]);
    },

    onClick : function(e){
        if(e.button != 0){
            return;
        }
        if(this.disabled){
            this.stopEvent(e);
        } else {
            if (this.fireEvent("click", this, e) !== false) {
                if(this.handler){
                    this.handler.call(this.scope || this, this, e);
                }
            }
        }
    },

    // private
    getHref: function() {
        var result = this.href;
        var p = Ext.urlEncode(Ext.apply(Ext.apply({}, this.baseParams), this.params));
        if (p.length) {
            result += ((this.href.indexOf('?') == -1) ? '?' : '&') + p;
        }
        return result;
    },

    /**
     * Sets the href of the link dynamically according to the params passed, and any {@link #baseParams} configured.
     * @param {Object} Parameters to use in the href URL.
     */
    setParams: function(p) {
        this.params = p;
        this.el.child(this.buttonSelector, true).href = this.getHref();
    }
});
Ext.reg('linkbutton', Ext.ux.LinkButton);

Ext.ns('Ext.ux.form');
Ext.ux.form.XCheckbox = Ext.extend(Ext.form.Checkbox, {
	submitOffValue: 'false',
	submitOnValue: 'true',
	onRender: function(){
	
		this.inputValue = this.submitOnValue;
		
		// call parent
		Ext.ux.form.XCheckbox.superclass.onRender.apply(this, arguments);
		
		// create hidden field that is submitted if checkbox is not checked
		this.hiddenField = this.wrap.insertFirst({
			tag: 'input',
			type: 'hidden'
		});
		
		// support tooltip
		if (this.tooltip) {
			this.imageEl.set({
				qtip: this.tooltip
			});
		}
		
		// update value of hidden field
		this.updateHidden();
		
	} // eo function onRender
	/**
	 * Calls parent and updates hiddenField
	 * @private
	 */
	,
	setValue: function(v){
		v = this.convertValue(v);
		this.updateHidden(v);
		Ext.ux.form.XCheckbox.superclass.setValue.apply(this, arguments);
	} // eo function setValue
	/**
	 * Updates hiddenField
	 * @private
	 */
	,
	updateHidden: function(v){
		v = undefined !== v ? v : this.checked;
		v = this.convertValue(v);
		if (this.hiddenField) {
			this.hiddenField.dom.value = v ? this.submitOnValue : this.submitOffValue;
			this.hiddenField.dom.name = v ? '' : this.el.dom.name;
		}
	} // eo function updateHidden
	/**
	 * Converts value to boolean
	 * @private
	 */
	,
	convertValue: function(v){
		return (v === true || v === 'true' || v == 1 || v === this.submitOnValue || String(v).toLowerCase() === 'on');
	} // eo function convertValue
}); // eo extend
// register xtype
Ext.reg('xcheckbox', Ext.ux.form.XCheckbox);

// create namespace for plugins
Ext.namespace('Ext.ux.plugins');

Ext.ux.plugins.IconCombo = function(config){
	Ext.apply(this, config);
};

// plugin code
Ext.extend(Ext.ux.plugins.IconCombo, Ext.util.Observable, {
	init: function(combo){
		Ext.apply(combo, {
			tpl: '<tpl for=".">' +
			'<div class="x-combo-list-item ux-icon-combo-item ' +
			'{' +
			combo.iconClsField +
			'}">' +
			'{' +
			combo.displayField +
			'}' +
			'</div></tpl>',
			
			onRender: combo.onRender.createSequence(function(ct, position){
				// adjust styles
				this.wrap.applyStyles({
					position: 'relative'
				});
				this.el.addClass('ux-icon-combo-input');
				
				// add div for icon
				this.icon = Ext.DomHelper.append(this.el.up('div.x-form-field-wrap'), {
					tag: 'div',
					style: 'position:absolute'
				});
			}), // end of function onRender
			setIconCls: function(){
				var rec = this.store.query(this.valueField, this.getValue()).itemAt(0);
				if (rec) {
					this.icon.className = 'ux-icon-combo-icon ' + rec.get(this.iconClsField);
				}
			}, // end of function setIconCls
			setValue: combo.setValue.createSequence(function(value){
				this.setIconCls();
			})
		});
	} // end of function init
}); // end of extend
Ext.namespace('Vt.Common');

var tokenDelimiter = ':';

Vt.Common.storeProvince = {
	xtype: 'jsonstore',
	//	autoDestroy: true,
	url: '/Info/GetProvince',
	autoLoad: true,
	root: 'items',
	idProperty: 'ProvinciaID',
	fields: ['ProvinciaID', 'Nome']
};

Vt.Common.storeComuni = new Ext.data.JsonStore({
	xtype: 'jsonstore',
	//	autoLoad: true,
	url: '/Info/GetComuni',
	root: 'items',
	idProperty: 'ID',
	fields: ['ID', 'Nome', 'ProvinciaID']
});
Vt.Common.storeComuni.load();

Vt.Common.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>');

Vt.Common.provinceTpl.compile();

Vt.Common.resultListTpl = new Ext.XTemplate('<div class="vt-result-list">' +
'<tpl for=".">' +
'	<div class="vtt-restaurants-subtitle" style=""><img src="/Content/Images/Items/{ProvinciaID}.gif" alt=""><b>{ProvinciaNome} e Provincia</b></div>' +
'	<tpl for="Comuni">' +
'		<div style="white-space:normal;"><b>{Comune}</b></div>' +
'<tpl for="Items">' +
'<hr style=\"color:lightgray\" />' +
'{[ values.Latitude !== 0 || values.Longitude !== 0 ? "<a href=\'#map-panel\' ><img src=\'/Content/Images/mappa_toscana30.jpg\' style=\'float:left;\' /></a>" : ""]}' +
'<div style="float:left;margin-left: 1em;">' +
'<div id="item-{ID}" style="font-weight:bold;color: #950E28;" class="item-selector" >{Name}</div>' +
'<div style="">{Address} - {CAP}' +
'{[values.Localita ? ", Loc. " + values.Localita: ""]}' +
'{[values.Telefono ? ", Tel. " + values.Telefono: ""]}' +
'{[values.Fax ? ", Tel. " + values.Fax: ""]}' +
'</div>' +
'<div><a href="mailto:{EmailAlt}">{EmailAlt}</a></div>' +
'<div><a href="http://{Web}" target="_blank">{Web}</a></div>' +
'			</div>' +
'			<br  style="clear:both;" />' +
'		</tpl>' +
'		<br />' +
'	</tpl>' +
'	<br />' +
'</tpl>' +
'</div>').compile();

Vt.Common.OptionForm = Ext.extend(Ext.FormPanel, {
	resultListID: 'result-list',
	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: [{
				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.Common.storeComuni
			}, {
				xtype: 'textfield',
				id: 'nome',
				fieldLabel: 'Nome'
			}].concat(this.additionalItems)
		
		});
		Ext.apply(this, {
			buttons: [{
				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.Common.OptionForm.superclass.initComponent.call(this);
	},
	showHandler: function(b, e){
		//				alert(that);
		var resultList = Ext.getCmp(this.resultListID);
		var params = {};
		var provinciaID = Ext.getCmp('field-provincia').getValue();
		if (provinciaID) {
			params.provinciaID = provinciaID;
		}
		var comune = Ext.getCmp('comune').getValue();
		if (comune) {
			params.comune = comune;
		}
		var nome = Ext.getCmp('nome').getValue();
		if (nome) {
			params.nome = nome;
		}
		params = this.readAdditionalParams(this, params)
		resultList.getStore().load({
			params: params
		});
	}
});

Ext.reg('Vt.Common.OptionForm', Vt.Common.OptionForm);


Vt.Common.ResultList = Ext.extend(Ext.DataView, {

	id: 'result-list',
	store: Vt.Common.defaultStore,
	tpl: Vt.Common.resultListTpl,
	loadingText: 'Loading',
	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',
			
			contentContainerID: 'content-container'
		
		});
		Ext.apply(this, {});
		Vt.Common.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.Common.ResultList', Vt.Common.ResultList);

Vt.Common.MapPanel = Ext.extend(Ext.ux.BingMapPanel, {
	store: Vt.Common.defaultStore,
	hidden: true,
	localConfig: {
		itemName: 'ItemName',
		itemsName: 'ItemsName',
		resultViewerID: 'result-list'
	},
	
	initComponent: function(){
	
		Ext.applyIf(this, {
			id: 'map-panel',
			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
			},
			
			pinTpl: new Ext.XTemplate('<div onclick="Ldc.' + this.localConfig.itemsName + '.ContentContainer.ShowDetails({ID});">' +
			'	<div><b>{Address}</b></div>' +
			'	<div>{ComuneNome} - {CAP} - {ProvinciaID}</div>' +
			'	<div>Tel. {Telefono} - Fax {Fax}</div>' +
			'</div>' +
			'<div><a href="mailto:{EmailAlt}">{EmailAlt}</a></div>' +
			'<div><a href="http://{Web}" target="_blank">{Web}</a></div>')
		});
		
		Ext.apply(this, {});
		
		Vt.Common.ResultList.superclass.initComponent.call(this);
		
		this.pinTpl.compile();
		//			alert(this.store.storeId);
		
		this.store.on('load', function(store, records, options){
			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].Items.length; k++) {
						item = records[i].data.Comuni[j].Items[k];
						if (item.Latitude !== 0 && item.Longitude !== 0) {
							items.push(item);
						}
					}
				}
			}
			//	alert(records.length);
			this.displayMap(items);
		}, this);
	},
	
	displayMap: function(items){
		var bmap = this.getMap();
		var point;
		var layer = this.findLayer(this.localConfig.itemsName);
		if (layer) {
			bmap.DeleteShapeLayer(layer);
		}
		//		bmap.ClearInfoBoxStyles();
		
		layer = new VEShapeLayer();
		layer.SetTitle(this.localConfig.itemsName);
		for (var i = 0; i < items.length; i++) {
			if (items[i].Latitude > 180 || items[i].Longitude > 180) {
				continue
			}
			point = new VELatLong(items[i].Latitude, items[i].Longitude);
			var pin = new VEShape(VEShapeType.Pushpin, point);
			pin.SetTitle("<i>" + items[i].Name + "</i>");
			pin.SetDescription(this.pinTpl.applyTemplate(items[i]));
			pin.SetCustomIcon('/Content/MapIcons/icons/restaurant.png');
			layer.AddShape(pin);
		}
		//Specifying clustering
		//layer.SetClusteringConfiguration(VEClusteringType.Grid);
		bmap.AddShapeLayer(layer);
		bmap.SetMapView(layer.GetBoundingRectangle());
		this.show();
	}
	
});

Ext.reg('Vt.Common.MapPanel', Vt.Common.MapPanel);


Vt.Common.BtnPanel = Ext.extend(Ext.DataView, {

	id: 'btn-panel',
	readAdditionalParams: function(form, params){
		return params;
	},
	
	initComponent: function(){
		Ext.applyIf(this, {
			store: Vt.Common.storeProvince,
			tpl: Vt.Common.provinceTpl,
			width: 550,
			autoHeight: true,
			singleSelect: true,
			overClass: 'x-view-over',
			itemSelector: 'div.provincia-selector',
			emptyText: 'Nessun elemento'
		});
		Ext.apply(this, {});
		Vt.Common.BtnPanel.superclass.initComponent.call(this);
		
		this.on('selectionchange', function(dv, selections){
			//						alert('provinciaHandler');
			this.provinciaHandler(dv.getSelectedRecords()[0].data.ProvinciaID);
		});
	},
	provinciaHandler: function(provinciaID){
		//		alert('provinciaHandler');
		var resultViewer = Ext.getCmp(this.resultViewerID);
		var params = {
			provinciaID: provinciaID
		};
		var comune = Ext.getCmp('comune').getValue();
		if (comune) {
			params.comune = comune;
		}
		var nome = Ext.getCmp('nome').getValue();
		if (nome) {
			params.nome = nome;
		}
		params = this.readAdditionalParams(this, params);
		resultViewer.getStore().load({
			params: params
		});
	},
	resultViewerID: 'result-list'
});

Ext.reg('Vt.Common.BtnPanel', Vt.Common.BtnPanel);

