function openAdvancedSearch()
{
    var btn = Ext.getCmp('toggle_advanced_search_button');
    Ext.getCmp('listings_search_form').expand();

    btn.setHandler(closeAdvancedSearch);
    btn.setText('Mostra la ricerca semplice');
}

function closeAdvancedSearch()
{
    var btn = Ext.getCmp('toggle_advanced_search_button');
    Ext.getCmp('listings_search_form').collapse();

    btn.setHandler(openAdvancedSearch);
    btn.setText('Mostra la ricerca avanzata');
}

// Paginazione
var pagingListingToolbar = new Ext.PagingToolbar({
    pageSize: 25,
    store: userListingsStore,
    displayInfo: true,
    displayMsg: 'Stai vedendo gli immobili dal n.{0} al n.{1}, su un totale di {2} trovati',
    emptyMsg: 'Nessun immobile corrispondente ai criteri di ricerca'
});

// Colore del testo di un annuncio disabilitato
var inactiveListingColor = '#dddddd';

// Colonne della tabella
var listingsColumns = [
    {
        header: 'Codice',
        dataIndex: 'codice',
        tooltip: 'Codice di riferimento immobile',
        width: 25,
        resizable: false,
        renderer: function (value, cell, record) {
            var html = value;
            if (record.data.active == 0)
                html = '<span style="color:' + inactiveListingColor + '">' + html + '</span>';

            return '<b>' + html + '</b>';
        }
    },
    /*
    {
        id: 'titolo',
        header: 'Immobile',
        dataIndex: 'titolo',
        tooltip: 'Immobile',
        width: 100,
        resizable: false,
        renderer: function (value, cell, record) {
            var html = Ext.util.Format.ellipsis(value, 100);
            if (record.data.active == 0)
                html = '<span style="color:' + inactiveListingColor + '">' + html + '</span>';

            return '<b>' + html + '</b>';
        }
    },
    */
    {
        id: 'tipologia',
        header: 'Tipologia',
        dataIndex: 'tipologia',
        tooltip: 'Tipologia',
        width: 100,
        resizable: false,
        renderer: function (value, cell, record) {
            var html = value;

            if (record.data.edificio)
                html += ' - ' + record.data.edificio;

            if (record.data.active == 0)
                html = '<span style="color:' + inactiveListingColor + '">' + html + '</span>';

            return '<b>' + html + '</b>';
    	}
    },
    {
    	header: 'Posizione',
        dataIndex: 'zona',
        resizable: false,
        width: 100,
        tooltip: 'Zona nel quale risiede questo immobile',
        renderer: function (value, cell, record) {
            var html = record.data.comune;
            
            if (value) 
                html += ' - ' + value;

            if (record.data.quartiere)
                html += ' - ' + record.data.quartiere;

            if (record.data.active == 0)
                html = '<span style="color:' + inactiveListingColor + '">' + html + '</span>';

            return '<b>' + html + '</b>';
    	}
    },
    {
        header: 'Prezzo',
        dataIndex: 'prezzo',
        width: 30,
        tooltip: 'Prezzo indicativo',
        resizable: false,
        renderer: function (value, cell, record) {
            var px = 'Trattativa riservata';

            if (record.data.prezzo_visibile == 1)
            {
                var v = String(value);
                var newprice = '';
                var cont = 0;

                for (var i = 0; i < v.length; i++)
                {
                    var j = v.length - 1 - i;
                    var c = v.charAt(j);
                    //alert('Nuovo carattere: ' + c);
                    newprice = c + newprice;
                    //alert('Nuova stringa: ' + newprice);
                    if (cont == 2 && i != (v.length - 1))
                    {
                        newprice = '.' + newprice;
                        //alert('Nuova stringa: ' + newprice);
                        cont = 0;
                    }
                    else
                    {
                        cont++;
                    }
                }

                px = '<b>&euro; ' + newprice + '</b>';
            }

            return px;
        }
    },
    {
        header: 'Opzioni',
        width: 25,
        resizable: false,
        renderer: function (value, cell, record) {
            //var htmlCode = '<a title="Leggi i dettagli di: ' + record.data.sef_title + '" href="' + baseApplicationUrl + '/immobile/' + record.data.sef_title + '"><img alt="' + record.data.sef_title + '" src="/img/icons/32/search.png" /></a>';
            var htmlCode = '<a toptions="type = iframe, effect = fade, width = 800, height = 600, overlayClose = 1" href="' + baseApplicationUrl + '/immobile/' + record.data.sef_title + '"><img title="Guarda scheda immobile" alt="Guarda scheda immobile" src="/img/icons/32/view.png" /></a>';
            htmlCode += '&nbsp;';
            htmlCode += '<a href="mailto:' + User.email + '?subject=Richiesta immobile codice riferimento ' + record.data.codice + '&body=Vorrei avere alcune informazioni in merito..."><img title="Richiedi informazioni" alt="Richiedi informazioni" src="/img/icons/32/email.png" /></a>';
            //htmlCode += '<a href="javascript:insertNewRequest(' + record.data.id + ')"><img alt="Richiedi informazioni" src="/img/icons/32/new_request.png" /></a>';

            return htmlCode;
        }
    }
];

// Grid
Sid.ListingsGrid = Ext.extend(Ext.grid.GridPanel, {
    initComponent: function () {
        var config = {
            layout: 'fit',
            stripeRows: true,
            autoScroll: true,
            view: new Ext.grid.GridView({
                forceFit: true,
                enableRowBody: true,
                showPreview: true,
                emptyText: 'Nessun immobile corrispondente ai criteri di ricerca',
                getRowClass: function (record, rowIndex, p, store) {
                    if (this.showPreview && record.data.active == 1)
                    {
                        var listingObject = record.data;
                        p.body = '';

                        if (listingObject.fotografie.length)
                        {
                            var gallery = '';

                            for (var i = 0; i < listingObject.fotografie.length; i++)
                            {
                                var photo = listingObject.fotografie[i];

                                if (photo)
                                {
                                    var didascalia = photo.didascalia;
                                    var nomefile = photo.nomefile;
                                    var divStyle = i < maxPhotosPreviewPerListing ? '' : ' style="display:none" ';

                                    Ext.ux.Lightbox.register('a.listing_' + listingObject.id, true); // true to show them as a set
                                    gallery += '<div ' + divStyle + ' class="thumbnail"><a href="' + imagesUrl + '/listing_' + listingObject.id + '/photos/mediumres/' + nomefile + '" rel="lightbox" title="' + didascalia + '" class="listing_' + listingObject.id + '"><img src="' + imagesUrl + '/listing_' + listingObject.id + '/photos/lowres/' + nomefile + '" alt="' + didascalia + '" /></a></div>';
                                }
                            }

                            listingObject.gallery = gallery;
                            
                        }

                        p.body = listingPreviewTemplatePhotos.apply(listingObject);

                        return 'x-grid3-row-expanded';
                    }

                    return 'x-grid3-row-collapsed';
                }
            }),
            autoExpandColumn: 'tipologia'
        };

        // apply config
        Ext.apply(this, Ext.apply(this.initialConfig, config));

        Sid.ListingsGrid.superclass.initComponent.apply(this, arguments);
    },

    onRender: function () {
        this.store.load();

        Sid.ListingsGrid.superclass.onRender.apply(this, arguments);
    }
});

Ext.reg('userlistingsgrid', Sid.ListingsGrid);

var userListings = new Sid.ListingsGrid({
    id: 'user_listings_tab',
    region: 'center',
    store: userListingsStore,
    title: 'Immobili',
    cm: new Ext.grid.ColumnModel({
        defaults: {
            sortable: true,
            menuDisabled: true,
            width: 50
        },
        resizable: false,
        columns: listingsColumns
    }),
    margins: '5 5 5 0',
    bbar: pagingListingToolbar,
    tbar: [
        {
            text: 'Cerca',
            icon: '/img/icons/24/search.png',
            iconAlign: 'left',
            scale: 'medium'
        },
        ' ',
        {
            xtype: 'textfield',
            width: 400,
            id: 'listing_text_filter',
            enableKeyEvents: true,
            selectOnFocus: true,
            listeners: {
                'keydown': function (field, evt) {
                    var btn = evt.getKey();
                    var val = field.getValue();

                    if (btn == evt.ENTER)
                    {
                        userListingsStore.load({
                            params: {
                                text: val,
                                action: 'read', // chiedo la lista
                                agency_id: User.agencyId // agenzia alla quale fa capo l'attuale utente
                            }
                        });
                    }
                }
            }
        },
        ' ',
        '-',
        {
            xtype: 'button',
            id: 'reset_search_listings_button',
            text: 'Vedi tutti',
            icon: '/img/icons/24/listings.png',
            iconAlign: 'left',
            scale: 'medium'
        },
        '->',
        '-',
        {
            xtype: 'button',
            id: 'toggle_advanced_search_button',
            text: 'Mostra la ricerca semplice',
            handler: closeAdvancedSearch
        }
    ]
});
