var Metrosplash;

if(!Metrosplash.component) { Metrosplash.component = {}; }

Metrosplash.component.LocationList = function(location_type, location_capability) {
    
    Ext.QuickTips.init();
    var postUrl = "/generic-requests/locations.php";

    var stateList = new Ext.data.Store({
        url: postUrl,
        reader: new Ext.data.JsonReader({
            root: 'data',
            totalProperty: 'totalCount',
            id: 'short'
        }, [
            {name: 'short'},
            {name: 'full'},
            {name: 'count'}
        ]),
        sortInfo: {
            field: 'short',
            direction: 'ASC'
        },
        baseParams: {
            type: 'location',
            lang: 'json'
        }
    });

    stateList.on('load', function() {
        locationDataStore.baseParams.state = this.data.items[0].id;
        locationDataStore.load({ params: { start: 0 } });
        stateCombo.setValue( this.data.items[0].id );
        if(cityCombo.rendered)
        {
            cityCombo.clearValue();
        }              
        cityList.load({ params: { state: this.data.items[0].id }});        
    });
    
    
    stateList.baseParams.action = 'stateList';
    stateList.baseParams.location_type = location_type;
    stateList.baseParams.location_capability = location_capability;
    stateList.load();
    
    
    var cityList = new Ext.data.Store({
        url: postUrl,
        reader: new Ext.data.JsonReader({
            root: 'data',
            totalProperty: 'totalCount',
            id: 'city'
        }, [
            {name: 'city'},
            {name: 'count'}
        ]),
        sortInfo: {
            field: 'city',
            direction: 'ASC'
        },
        baseParams: {
            type: 'location',
            lang: 'json'
        }
    });
    
    cityList.baseParams.action = 'cityList';
    cityList.baseParams.location_type = location_type;
    cityList.baseParams.location_capability = location_capability;
    
    // Custom rendering Template
    
    var stateCombo = new Ext.form.ComboBox({
        fieldLabel:    'Type',
        hiddenName:    'state',
        
        emptyText:     'Select a state...',
        
        displayField:  'full',
        valueField:    'short',
        
        mode:          'local',
        triggerAction: 'all',
        fieldLabel:    'State: ',
        
        allowBlank: true,
        typeAhead: true,
        hideTrigger: false,
        editable: true,
        invalidClass: '',
            
        tpl: new Ext.XTemplate(
            '<tpl for="."><div class="x-combo-list-item" ext:qtip="Locations in {full}: {count}">',
                '{full} - <span>({count})</span></h3>',
            '</div></tpl>'
        ),
        listWidth: 200,
        
        onSelect: function(record){ // override default onSelect reload location store
            locationDataStore.baseParams.state = record.id;
            locationDataStore.baseParams.city = null;
            locationDataStore.load({ params: { start: 0 }});
            cityCombo.clearValue(); 
            cityList.load({ params: { state: record.id }});
            this.setValue(record.id);
            this.collapse();             
        },
        store: stateList
    });
    
    
    
    var locationDataStore = new Ext.data.Store({
        url: postUrl,
        reader: new Ext.data.JsonReader({
            root: 'data',
            totalProperty: 'totalCount',
            id: 'location_id'
        }, [
            {name: 'location_id'},
            {name: 'name',  mapping: 'partner_name'},
            {name: 'address', mapping: 'address1' },
            {name: 'city'},
            {name: 'state'},
            {name: 'zip', mapping: 'zipcode'}
        ]),
        baseParams: {
            type: 'location',
            lang: 'json',
            limit: 16
        }
    });
    
    locationDataStore.baseParams.action = 'search';
    locationDataStore.baseParams.location_type = location_type;
    locationDataStore.baseParams.location_capability = location_capability;
    
    
    var cityCombo = new Ext.form.ComboBox({
        fieldLabel:    'City',
        hiddenName:    'city',
        
        emptyText:     'Select a city...',
        
        displayField:  'city',
        valueField:    'city',
        
        mode:          'local',
        triggerAction: 'all',
        fieldLabel:    'City: ',
        
        allowBlank: true,
        typeAhead: true,
        hideTrigger: false,
        editable: true,
        invalidClass: '',
        selectOnFocus: true,
        triggerAction: 'all',
        
        tpl: new Ext.XTemplate(
            '<tpl for="."><div class="x-combo-list-item" ext:qtip="Locations in {city}: {count}">',
                '{city} - <span>({count})</span>',
            '</div></tpl>'
        ),
        listWidth: 200,
        //tpl: resultTpl,
        onSelect: function(record){ // override default onSelect reload location store
            locationDataStore.baseParams.city = record.data.city;
            locationDataStore.load({ params: { start: 0 }});
            this.setValue(record.data.city);
            this.collapse();            
        },
        store: cityList
    });    

    stateCombo.on('keypress', function(e) { 
        if(e.getKey() == e.ENTER && this.getValue().length > 0) 
        {
            locationDataStore.baseParams.state = record.id;
            locationDataStore.load({ params: { start: 0 } });
            
            cityCombo.clearValue(); 
            cityList.load({ params: { state: record.id }});
        
            this.setValue(record.id);
            this.collapse();
        }
    });
    
    cityCombo.on('keypress', function(e) { 
        if(e.getKey() == e.ENTER && this.getValue().length > 0) 
        {
            locationDataStore.baseParams.city = record.data.city;
            locationDataStore.load({ params: { start: 0 } });
            
            this.setValue(record.data.city);
            this.collapse();
        }
    });  



    var tpl = new Ext.XTemplate(
	'<tpl for=".">',
            '<div class="location-wrap" id="{location_id}">',
                '<div class="location">',
                '<strong>{name}</strong>',
                '<br />',
                '{address}',
                '<br />',
                '{city}, {state} {zip}',
                '<br />',
                '<a href="/Search.php?locationId={location_id}&zipcode={zip}&radius=50">Map location...</a>',
                '<br />',
                '&nbsp;',
                '<br />',
            '</div></div>',
        '</tpl>',
        '<div class="x-clear"></div>'
	);
    config = {
        id:'locations',
        height: 514,
        // width: 700,
        collapsible:false,
        frame: false,
        title:'Locations by State:',
        items: new Ext.DataView({
            store: locationDataStore,
            tpl: tpl,
            width:680,
            layout: 'table',
            loadingText: 'Loading Locations...',
            itemSelector:'div.location-wrap',
            overClass: 'location-wrap-over',
            emptyText: 'No locations to display'            
        }),
        tbar: new Ext.Toolbar({ 
            items: [
                'State: ',
                stateCombo,
                ' ',
                '-',
                ' ',
                'City: ',
                cityCombo,
                ' ',
                '-',
                ' ',
                new Ext.Toolbar.Button({
                    handler: function() {
                        cityCombo.clearValue();
                        cityList.load({ params: { state: stateCombo.getValue() }});
                        locationDataStore.baseParams.city = null;
                        locationDataStore.load({ params: { start: 0 } });
                    },
                    text: 'Reset',
                    icon: '/generic-assets/ext2/resources/images/default/icons/fam/table_refresh.png',
                    cls: 'x-btn-text-icon'
                })], 
            style: {color: 'black'} 
        }),
        bbar:  new Ext.PagingToolbar({
            pageSize: 16,
            displayInfo: true,
            displayMsg: 'Locations {0} - {1} of {2}',
            emptyMsg: "No locations to display",
            store: locationDataStore,
            style: {color: 'black'}
        }) 
    }
    if(arguments.length > 2 && typeof(arguments[2]) == 'object') {
        if (arguments[3] && arguments[3] == true) {
            config = arguments[2];
        }
        else {
            for(var x in arguments[2])
            {
                config[x] = arguments[2][x];
            }
        }       
    }
    Metrosplash.component.LocationList.superclass.constructor.call(this, config);
}

Ext.extend(Metrosplash.component.LocationList, Ext.Panel);
