// Filtro per tipo di contratto
var contractFilterInput = new Ext.form.ComboBox({
    id: 'contract_filter_input',
    fieldLabel: 'Tipo di contratto',
    store: ContractsStore,
    displayField: 'nome',
    valueField: 'id',
    typeAhead: true,
    forceSelection: true,
    editable: false,
    mode: 'local',
    triggerAction: 'all',
    emptyText: 'Qualsiasi',
    xtype: 'combo'
});

// Filtro per prezzo minimo
var minPriceFilterInput = new Ext.form.NumberField({
    id: 'min_price_filter_input',
    fieldLabel: 'Da euro',
    minValue: 0,
    selectOnFocus: true,
    allowDecimals: false,
    enableKeyEvents: true
});

// Filtro per prezzo massimo
var maxPriceFilterInput = new Ext.form.NumberField({
    id: 'max_price_filter_input',
    fieldLabel: 'Prezzo massimo',
    minValue: 0,
    selectOnFocus: true,
    allowDecimals: false,
    enableKeyEvents: true
});

var roomsNumberFilterInput = new Ext.form.NumberField({
    id: 'min_rooms_filter_input',
    fieldLabel: 'Numero minimo di camere',
    minValue: 0,
    selectOnFocus: true,
    allowDecimals: false,
    enableKeyEvents: true
});

var bathsNumberFilterInput = new Ext.form.NumberField({
    id: 'min_baths_filter_input',
    fieldLabel: 'Numero minimo di bagni',
    minValue: 0,
    selectOnFocus: true,
    allowDecimals: false,
    enableKeyEvents: true
});

// Filtro per categoria
var categoryFilterInput = new Ext.form.ComboBox({
    id: 'category_filter_input',
    fieldLabel: 'Categoria',
    store: CategoriesStore,
    displayField: 'nome',
    emptyText: 'Qualsiasi',
    valueField: 'id',
    typeAhead: true,
    forceSelection: true,
    editable: false,
    mode: 'local',
    triggerAction: 'all',
    listeners: {
        'select': function (combo, record, index) {
            // Se cambia la categoria, resetto tutte le scelte che dipendono da lei (tipologia, edificio)
            buildingTypeFilterInput.reset();
            houseTypeFilterInput.reset();

            BuildingTypesStore.load({
                params: {
                    category_id: record.data.id
                },
                callback: function (r, options, success) {
                    if (success) {
                        Ext.getCmp('building_type_filter_input_container').show();
                    }
                }
            });

            HouseTypesStore.load({
                params: {
                    category_id: record.data.id
                },
                callback: function (r, options, success) {
                    if (success) {
                        houseTypeFilterInput.setDisabled(false);
                    }
                }
            });

            var residentialFilters = Ext.getCmp('residential_filters');
            if (record.data.id == 1)
            {
                residentialFilters.show();
            }
            else
            {
                roomsNumberFilterInput.reset();
                bathsNumberFilterInput.reset();

                // Nascondo i filtri specifici per la categoria residenziale
                residentialFilters.hide();
            }
        }
    }
});

// Filtro per edificio
var buildingTypeConfig = {
    id: 'buildingtypes_filter_input',
    fieldLabel: 'Sotto-categoria',
    store: BuildingTypesStore,
    displayField: 'nome',
    valueField: 'id',
    forceSelection: true,
    editable: false,
    typeAhead: true,
    mode: 'local',
    triggerAction: 'all',
    selectOnFocus: true,
    xtype: 'combo',
    title: 'Sotto-categorie',
    emptyText: 'Qualsiasi'
};

var buildingTypeFilterInput = new Ext.ux.MultiSelect(Ext.applyIf({
        //minLength: 2,
        multiSelect: true
    },
    buildingTypeConfig
));

// Filtro per tipologia
var houseTypeConfig = {
    id: 'housetypes_filter_input',
    fieldLabel: 'Tipologia',
    store: HouseTypesStore,
    displayField: 'nome',
    valueField: 'id',
    forceSelection: true,
    editable: false,
    disabled: true,
    typeAhead: true,
    mode: 'local',
    triggerAction: 'all',
    selectOnFocus: true,
    xtype: 'combo',
    title: 'Tipologie di immobile',
    emptyText: 'Qualsiasi'
};

var houseTypeFilterInput = new Ext.ux.MultiSelect(Ext.applyIf({
        //minLength: 2,
        multiSelect: true
    }, 
    houseTypeConfig
));

// Filtro per piano
var floorConfig = {
    id: 'floor_filter_input',
    fieldLabel: 'Piano',
    store: FloorsStore,
    displayField: 'nome',
    valueField: 'id',
    forceSelection: true,
    editable: false,
    typeAhead: true,
    mode: 'local',
    triggerAction: 'all',
    selectOnFocus: true,
    xtype: 'combo',
    anchor: '90%',
    title: 'Numero di piano',
    emptyText: 'Qualsiasi'
};

var floorFilterInput = new Ext.ux.MultiSelect(Ext.applyIf({
        //minLength: 2,
        multiSelect: true
    },
    floorConfig
));

// ***************** POSIZIONE E LOCALIZZAZIONE ********************************

var townFilterInput = new Ext.form.ComboBox({
    id: 'town_filter_input',
    editable: true,
    typeAhead: true,
    tpl: '<tpl for="."><div class="x-combo-list-item">{nome}</div></tpl>',
    hiddenName: 'towns',
    displayField: 'nome',
    valueField: 'id',
    mode: 'local',
    xtype: 'combo',
    name: 'town_name',
    fieldLabel: 'Comune',
    store: TownsStore,
    forceSelection: true,
    triggerAction: 'all',
    msgTarget: 'side',
    anchor: '90%',
    emptyText: 'Qualsiasi',
    title: 'Comuni disponibili',
    listeners: {
        blur: function(obj, e) {
            zoneFilterInput.clearValue();
            districtFilterInput.clearValue();

            ZonesStore.load({
                params: {
                    towns: parseInt(obj.getValue())
                }
            });

            DistrictsStore.load({
                params: {
                    towns: parseInt(obj.getValue())
                }
            });
        },
        select: function(combo, record, index) {
            zoneFilterInput.clearValue();
            districtFilterInput.clearValue();
            var val = combo.getValue();

            ZonesStore.load({
                params: {
                    towns: val
                }
            });

            DistrictsStore.load({
                params: {
                    towns: val
                }
            });
        }
    }
});

// Filtro per zona
var zoneConfig = {
    id: 'zones_filter_input',
    fieldLabel: 'Zone',
    store: ZonesStore,
    displayField: 'nome',
    valueField: 'id', 
    typeAhead: true,
    mode: 'local',
    triggerAction: 'all',
    forceSelection: true,
    editable: false,
    selectOnFocus: true,
    xtype: 'combo',
    emptyText: 'Qualsiasi',
    title: 'Zone',
    listeners: {
        'select': function (combo, record, index) {
            districtFilterInput.clearValue();

            DistrictsStore.load({
                params: {
                    zones: combo.getValue()
                }
            });
        }
    }
};
var zoneFilterInput = new Ext.ux.MultiSelect(Ext.applyIf({
        //minLength: 2,
        multiSelect: true
    }, 
    zoneConfig
));

// Filtro per quartiere
var districtConfig = {
    id: 'districts_filter_input',
    fieldLabel: 'Quartieri',
    store: DistrictsStore,
    displayField: 'nome',
    valueField: 'id', 
    typeAhead: true,
    mode: 'local',
    triggerAction: 'all',
    forceSelection: true,
    editable: false,
    selectOnFocus: true,
    xtype: 'combo',
    emptyText: 'Qualsiasi',
    title: 'Quartieri'
};
var districtFilterInput = new Ext.ux.MultiSelect(Ext.applyIf({
        //minLength: 2,
        multiSelect: true
    }, 
    districtConfig
));

// Distanza massima di ricerca
var distanceFilterInput = new Ext.form.ComboBox({
    id: 'distance_filter_input',
    fieldLabel: "Entro quanti km dall'indirizzo?",
    store: DistancesStore,
    value: distanceFilterDefault,
    displayField: 'km',
    emptyText: 'Illimitati',
    valueField: 'id',
    typeAhead: true,
    forceSelection: true,
    editable: false,
    mode: 'local',
    triggerAction: 'all'
});

// Indirizzo
var addressFilterInput = new Ext.form.TextField({
    id: 'address_filter_input',
    fieldLabel: "Vicino all'indirizzo",
    xtype: 'textfield',
    width: 150,
    selectOnFocus: true,
    value: searchParams.address,
    //tabIndex: 1,
    allowBlank: true,
    enableKeyEvents: true
});

// Pulsante di avvio ricerca
var searchListingsButton = new Ext.Button({
    id: 'search_listings_button',
    text: 'Cerca',
    icon: '/img/icons/24/search.png',
    iconAlign: 'left',
    scale: 'medium'
});

// Pulsante di re-inizio ricerca
var resetSearchListingsButton = new Ext.Button({
    text: 'Vedi tutti',
    icon: '/img/icons/24/listings.png',
    iconAlign: 'left',
    scale: 'medium'
});

// Form
var listingsSearchForm = new Ext.FormPanel({
    id: 'listings_search_form',
    region: 'west',
    width: 200,
    split: true,
    labelAlign: 'top',
    frame: true,
    autoScroll: true,
    //animCollapse: false,
    layout: 'accordion',
    collapsed: !User.prefs.visibleAdvancedSearch,
    collapsible: true,
    margins: '5 0 5 5',
    cmargins: '5 5 5 5',
    title: 'Ricerca avanzata',
    items: [
        {
            title: 'Dati generici',
            xtype: 'fieldset',
            style: 'background-color:white',
            autoHeight: true,
            defaultType: 'textfield',
            defaults: {
                anchor: '90%'
            },
            items: [
                categoryFilterInput,
                {
                    id: 'building_type_filter_input_container',
                    xtype: 'container',
                    hidden: true,
                    anchor: '100%',
                    layout: 'form',
                    defaults: {
                        anchor: '90%'
                    },
                    items: buildingTypeFilterInput
                },
                {
                    id:'residential_filters',
                    xtype: 'container',
                    layout: 'form',
                    autoHeight: true,
                    hidden: true,
                    defaultType: 'textfield',
                    defaults: {
                        anchor: '90%'
                    },
                    items: [
                        houseTypeFilterInput,
                        roomsNumberFilterInput,
                        bathsNumberFilterInput
                    ]
                }
            ]
	},
        {
            title: 'Dati economici',
            xtype: 'fieldset',
            style: 'background-color:white',
            autoHeight: true,
            defaultType: 'textfield',
            defaults: {
                anchor: '90%'
            },
            items: [
                contractFilterInput,
                //minPriceFilterInput,
                maxPriceFilterInput
            ]
        },
	{
            title: 'Posizione',
            xtype: 'fieldset',
            style: 'background-color:white',
            autoHeight: true,
            items: [
                {
                    layout: 'column',
                    xtype: 'container',
                    items: [
                        {
                            columnWidth: 0.5,
                            xtype: 'container',
                            layout: 'form',
                            defaults: {
                                            anchor: '90%'
                            },
                            items: [
                                {
                                    xtype: 'radio',
                                    id: '',
                                    checked: true,
                                    name: 'geofilter',
                                    hideLabel: true,
                                    boxLabel: 'Per zona',
                                    listeners: {
                                        'focus': function () {
                                            Ext.getCmp('zones_filters').show();
                                            Ext.getCmp('address_filters').hide();
                                            Ext.getCmp('address_filter_input').setValue(addressFilterDefault);
                                            Ext.getCmp('distance_filter_input').setValue(distanceFilterDefault);
                                        }
                                    }
                                }
                            ]
                        },
                        {
                            columnWidth: 0.5,
                            xtype: 'container',
                            layout: 'form',
                            defaults: {
                                anchor: '90%'
                            },
                            items: [
                                {
                                    xtype: 'radio',
                                    name: 'geofilter',
                                    hideLabel: true,
                                    boxLabel: 'Indirizzo',
                                    listeners: {
                                        'focus': function () {
                                            Ext.getCmp('address_filters').show();
                                            Ext.getCmp('zones_filters').hide();
                                            Ext.getCmp('zones_filter_input').clearValue();
                                        }
                                    }
                                }
                            ]
                        }
                    ]
                },
                townFilterInput,
                {
                    xtype: 'container',
                    id: 'zones_filters',
                    layout: 'form',
                    defaults: {
                        anchor: '90%'
                    },
                    items: [
                        zoneFilterInput,
                        districtFilterInput
                    ]
                },
                {
                    xtype: 'container',
                    id: 'address_filters',
                    layout: 'form',
                    defaults: {
                        anchor: '90%'
                    },
                    hidden: true,
                    items: [
                        addressFilterInput,
                        distanceFilterInput
                    ]
                },
                floorFilterInput
            ]
        }
    ],
    buttons: [
        searchListingsButton,
        resetSearchListingsButton
    ],
    listeners: {
        'expand': function () {
            TownsStore.load();
            ZonesStore.load();
            DistrictsStore.load();
            BuildingTypesStore.load();
            
            townFilterInput.reset();
            zoneFilterInput.clearValue();
            districtFilterInput.clearValue();
            buildingTypeFilterInput.clearValue();
        }
    }
});
