/*
 * LINGUIST.LLMAP.QuickMap
 * Written by Benjamin J Cool <ben@linguistlist.org>
 *
 * Base class for frequent query named Quick Map
 * uses some components of layer.js
 */

LINGUIST.LLMAP.QuickMap = Ext.extend(Ext.Window, {
    constructor: function(config) {

        this.map = config.map;

        this.about_quickmap = new Ext.Window({
            title: 'About Quickmap',
            closable: true,
            width: 400,
            autoHeight: true,
            autoLoad: 'quickmap.html',
            listeners: {
                scope: this,
                beforeclose: function(){
                    this.about_quickmap.hide();
                }
            }
        });

        this.languages = new Ext.data.Store({
            autoLoad: false,
            proxy: new Ext.data.HttpProxy({
                url: '/languages.json',
                method: 'GET'
            }),
            reader: new Ext.data.JsonReader({
                fields: [ 'id', 'name', 'family' ],
                root: 'data'
            })
        });

        this.families = new Ext.data.Store({
            autoLoad: true,
            proxy: new Ext.data.HttpProxy({
                url: '/families.json',
                method: 'GET'
            }),
            reader: new Ext.data.JsonReader({
                fields: [ 'family' ],
                root: 'data'
            })
        });

        this.nameCombo = new Ext.form.ComboBox({
            store: this.languages,
            displayField: 'name',
            allowBlank: false,
            forceSelection: true,
            valueField: 'id',
            tpl: new Ext.XTemplate(
                '<tpl for="."><div class="search-item">',
                '<p>Language Name: {name}</p>',
                '<p>Language Code: {id}</p>',
                '<p>Family: {family}</p></div></tpl>'),
            itemSelector: 'div.search-item',
            hideTrigger: true,
            emptyText: 'Select a Language By Proper Name...',
            fieldLabel: 'Language Name',
            typeAhead: false,
            hideLabel: true,
            anchor: '100%',
            //mode: 'local',
            minChars: 2,
            queryParam: 'name',
            listeners: {
                scope: this,
                select: function(combo,record,index){
                    //this.fireEvent('language',{id: record.get("id")});
                    //this.countryds.load({params: {id: this.nameCombo.getValue()}});
                    //this.nameCombo.setValue("");
                }
            }
        });

        this.countryExpander = new Ext.grid.RowExpander({
            tpl : new Ext.Template(
                '<p><span style="font-weight: bold">Country Name:</span> {country}</p>'+
                    '<p><span style="font-weight: bold">Language Name:</span> {language}</p>'+
                    '<p><span style="font-weight: bold">Language Population:</span> {pop}</p>'+
                    '<p><span style="font-weight: bold">ISO Code: {language_code} </span> <a href="/languages/{language_code}/data_browser.html" target="_browser"><b>See resources on this language.</b></a></p>'+
                '<p><a href="#">Double Click to zoom to {language} on the map.</a></p>')
        });

        this.langExpander = new Ext.grid.RowExpander({
          tpl : new Ext.Template('<p><span style="font-weight: bold">Country Name:</span> {country}</p>',
                '<p><span style="font-weight: bold">Language Name:</span> {language}</p>',
                '<p><span style="font-weight: bold">Language Population:</span> {pop}</p>',
                '<p><span style="font-weight: bold">ISO Code: {language_code} </span> <a href="/languages/{language_code}/data_browser.html" target="_browser"><b>See resources on this language.</b></a></p>',
            '<p><a href="#">Double Click to zoom to {language} on the map.</a></p>')
        });

        this.langExpander2 = new Ext.grid.RowExpander({
          tpl : new Ext.Template('<p><span style="font-weight: bold">Country Name:</span> {country}</p>',
                '<p><span style="font-weight: bold">Language Name:</span> {language}</p>',
                '<p><span style="font-weight: bold">Language Population:</span> {pop}</p>',
                '<p><span style="font-weight: bold">ISO Code: {language_code} </span> <a href="/languages/{language_code}/data_browser.html" target="_browser"><b>See resources on this language.</b></a></p>',
            '<p><a href="#">Double Click to zoom to {language} on the map.</a></p>')
        });

        this.countryds = new Ext.data.Store({
            autoLoad: true,
            proxy: new Ext.data.HttpProxy({
                url: '/languages/---/countries.json',
                method: 'GET'
            }),
            reader: new Ext.data.JsonReader({
                root: 'data',
                fields: [ 'id_iso_a3', 'country_code', 'country', 'language_code', 'language', 'pop']
            })
        });

        this.countries = new Ext.data.Store({
            autoLoad: true,
            proxy: new Ext.data.HttpProxy({
                url: '/countries.json',
                method: 'GET'
            }),
            reader: new Ext.data.JsonReader({
                fields: [ 'id', 'country' ],
                root: 'data'
            })
        });

        this.langds = new Ext.data.Store({
            autoLoad: false,
            proxy: new Ext.data.HttpProxy({
                url: '/countries/---/languages.json',
                method: 'GET'
            }),
            reader: new Ext.data.JsonReader({
                root: 'data',
                fields: [ 'id_iso_a3', 'country_code', 'country', 'language_code', 'language', 'pop' ]
            })
        });

        this.langfamilyds = new Ext.data.Store({
            autoLoad: false,
            proxy: new Ext.data.HttpProxy({
                url: '/families/---/languages.json',
                method: 'GET'
            }),
            reader: new Ext.data.JsonReader({
                root: 'data',
                fields: [ 'id_iso_a3', 'country_code', 'country', 'language_code', 'language', 'pop' ]
            })
        });

        this.countryCombo = new Ext.form.ComboBox({
            store: this.countries,
            displayField: 'country',
            valueField: 'id',
            allowBlank: false,
            forceSelection: true,
            anchor: '100%',
            emptyText: 'Select a Country...',
            typeAhead: false,
            hideLabel : true,
            hideTrigger: true,
            mode: 'local',
            listeners: {
                scope: this,
                select: function(combo,record,index){
                    //this.fireEvent('country',{id: record.get("id")});
                    //this.langds.load({params: {id: this.countryCombo.getValue()}});
                    //this.combo.setValue("");
                }
            }
        });

        this.familyCombo = new Ext.form.ComboBox({
            store: this.families,
            displayField: 'family',
            valueField: 'family',
            allowBlank: false,
            forceSelection: true,
            hideTrigger: true,
            anchor: '100%',
            emptyText: 'Select a Family...',
            typeAhead: false,
            hideLabel: true,
            mode: 'local',
            listeners: {
                scope: this,
                select: function(combo,record,index){
                    //this.fireEvent('country',{id: record.get("id")});
                    //this.langds.load({params: {id: this.countryCombo.getValue()}});
                    //this.combo.setValue("");
                }
            }
        });

        LINGUIST.LLMAP.QuickMap.superclass.constructor.call(this, {
            title: 'Quick Map: Data from <a href="http://www.gmi.org/">Global Mapping International</a>',
            width: 350,
            height: 250,
            layout: 'card',
            defaults: {
                border: false
            },
            activeItem: 0,
            items: [
                {
                    id: 'card-0',
                    layout: 'anchor',
                    bodyStyle: 'padding: 15px',
                    items: [
                        {
                            'style': 'margin: 15px',
                            'xtype': 'button',
                            'text': 'Find Languages by Name',
                            'scope': this,
                            'handler': function(){
                                this.layout.setActiveItem(1);
                            }
                        },
                        {
                            'style': 'margin: 15px',
                            'xtype': 'button',
                            'text': 'Find Languages by Country',
                            'scope': this,
                            'handler': function(){
                                this.layout.setActiveItem(3);
                            }
                        },
                        {
                            'style': 'margin: 15px',
                            'xtype': 'button',
                            'text': 'Find Language Families',
                            'scope': this,
                            'handler': function(){
                                this.layout.setActiveItem(5);
                            }
                        },
                        {
                            'style': 'margin: 15px',
                            'xtype': 'button',
                            'text': 'About QuickMap',
                            'scope': this,
                            'handler': function(){
                                this.about_quickmap.show();
                            }
                        }
                    ]
                },
                {
                    id: 'card-1',
                    layout: 'anchor',
                    items: [
                        this.nameCombo,
                        {
                            html: "<ol style=\"list-style-type: decimal !important; list-style-position: inside !important;\" ><li>Start typing a language name into the box above.</li><li>Select a language from the list that appears.</li><li>Click &quot;Next&quot; to map the chosen language.</li></ol>",
                            border: false,
                            bodyStyle: 'padding: 5px;'
                        }
                    ],
                    bodyStyle: 'padding: 15px',
                    bbar: [
                        {
                            text: '<<',
                            scope: this,
                            handler: function(){this.layout.setActiveItem(0);}
                        },
                        '->', // greedy spacer so that the buttons are aligned to each side
                        {
                            text: 'Next >',
                            scope: this,
                            handler: function(){
                            	if(this.nameCombo.isValid() && this.nameCombo.getValue() != ""){
									this.countryds.proxy.conn.url = '/languages/' + this.nameCombo.getValue() + '/countries.json';
									this.countryds.load();
	
									this.items.items[2].setTitle('Where '+this.nameCombo.getRawValue()+' is spoken (data from GMI)');
									this.makeLanguageMap(this.nameCombo.getValue());
									this.layout.setActiveItem(2);
                                }
                            }
                        }
                    ]
                },
                {
                    id: 'card-2',
                    xtype: 'grid',
                    title: 'temp',
                    ds: this.countryds,
                    plugins: this.countryExpander,
                    autoExpandColumn: 'id',
                    columns: [
                        this.countryExpander,
                        {id: 'id',header: 'Country',dataIndex: 'country',sortable: true}
                    ],
                    listeners: {
                        scope: this,
                        rowdblclick: function(grid, index, e){
                            this.zoomToCountry(grid.getSelectionModel().getSelected().data.id_iso_a3.substr(4));
                        }
                    },
                    bbar: [
                        {
                            text: '<<',
                            scope: this,
                            handler: function(){this.layout.setActiveItem(0);}
                        },
                        {
                            text: '< Back',
                            scope: this,
                            handler: function(){this.layout.setActiveItem(1);}
                        }
                    ]
                },
                {
                    id: 'card-3',
                    layout: 'anchor',
                    items: [
                        this.countryCombo,
                        {
                            html: "<ol style=\"list-style-type: decimal !important; list-style-position: inside !important;\" ><li>Start typing a country name into the box above.</li><li>Select a country from the list that appears.</li><li>Click &quot;Next&quot; to map the chosen country and the languages spoken there.</li></ol>",
                            border: false,
                            bodyStyle: 'padding: 5px;'
                        }
                    ],
                    bodyStyle: 'padding: 15px',
                    bbar: [
                        {
                            text: '<<',
                            scope: this,
                            handler: function(){this.layout.setActiveItem(0);}
                        },
                        '->', // greedy spacer so that the buttons are aligned to each side
                        {
                            text: 'Next >',
                            scope: this,
                            handler: function(){
                                if(this.countryCombo.isValid() && this.countryCombo.getValue() != ""){
									this.makeCountryMap(this.countryCombo.getValue());
									this.items.items[4].setTitle("Languages of "+this.countryCombo.getRawValue()+' (data from GMI)');
	
									this.langds.proxy.conn.url = '/countries/' + this.countryCombo.getValue() + '/languages.json';
									this.langds.load();
	
									this.layout.setActiveItem(4);
								}
                            }
                        }
                    ]
                },
                {
                    id: 'card-4',
                    xtype: 'grid',
                    title: 'temp',
                    ds: this.langds,
                    plugins: this.langExpander,
                    autoExpandColumn: 'id',
                    columns: [
                        this.langExpander,
                        {id: 'id',header: 'Language Name',dataIndex: 'language',sortable: true}
                    ],
                    listeners: {
                        scope: this,
                        rowdblclick: function(grid, index, e){
                            this.zoomToLanguage(grid.getSelectionModel().getSelected().data.id_iso_a3);
                        }
                    },
                    bbar: [
						{
                            text: '<<',
                            scope: this,
                            handler: function(){this.layout.setActiveItem(0);}
                        },
                        {
                            text: '< Back',
                            scope: this,
                            handler: function(){this.layout.setActiveItem(3);}
                        }
                    ]
                },
                {
                    id: 'card-5',
                    layout: 'anchor',
                    items: [
                        this.familyCombo,
                        {
                            html: "<ol style=\"list-style-type: decimal !important; list-style-position: inside !important;\" ><li>Start typing a language family into the box above.</li><li>Select a language family from the list that appears.</li><li>Click &quot;Next&quot; to map the chosen language family.</li></ol>",
                            border: false,
                            bodyStyle: 'padding: 5px;'
                        }
                    ],
                    bodyStyle: 'padding: 15px',
                    bbar: [
                        {
                            text: '<<',
                            scope: this,
                            handler: function(){this.layout.setActiveItem(0);}
                        },
                        '->', // greedy spacer so that the buttons are aligned to each side
                        {
                            text: 'Next >',
                            scope: this,
                            handler: function(){
                                if(this.familyCombo.isValid() && this.familyCombo.getValue() != ""){
									this.makeFamilyMap(this.familyCombo.getValue());
									this.items.items[6].setTitle("Languages of "+this.familyCombo.getRawValue()+' (data from GMI)');
	
									this.langfamilyds.proxy.conn.url = '/families/' + this.familyCombo.getValue() + '/languages.json';
									this.langfamilyds.load();
	
									this.layout.setActiveItem(6);
								}
                            }
                        }
                    ]
                },
                {
                    id: 'card-6',
                    xtype: 'grid',
                    title: 'temp',
                    ds: this.langfamilyds,
                    plugins: this.langExpander2,
                    autoExpandColumn: 'id',
                    columns: [
                        this.langExpander2,
                        {id: 'id',header: 'Language Name',dataIndex: 'language',sortable: true}
                    ],
                    listeners: {
                        scope: this,
                        rowdblclick: function(grid, index, e){
                            this.zoomToLanguage(grid.getSelectionModel().getSelected().data.id_iso_a3);
                        }
                    },
                    bbar: [
                        {
                            text: '<<',
                            scope: this,                        	
                        	handler: function(){
                        		this.layout.setActiveItem(0);
                        	}
                        },
                        {
                            text: '< Back',
                            scope: this,
                            handler: function(){this.layout.setActiveItem(5);}
                        }
                    ]
                }
            ],
            keys: {
                key: Ext.EventObject.ESC,
                scope: this,
                fn: function () { this.hide(); }
            },
            listeners: {
                scope: this,
                beforeclose: function(){
                    this.hide();
                }
            }
        });
    },

    makeCountryMap: function(id){
        Ext.Ajax.request({
            url: '/countries/' + id + '.json',
            scope: this,
            success: function(response,options){
                var result  = Ext.decode(response.responseText);
                var country = result.data;

                this.map.zoomToBounds(country.minx, country.miny, country.maxx, country.maxy);

                this.map.addService(new LINGUIST.LLMAP.WMSService({
                    canonical_name: 'QuickMap: ' + country.country,
                    url: 'http://maggie.linguistlist.org/geoserver/wms?',
                    minx: country.minx,
                    miny: country.miny,
                    maxx: country.maxx,
                    maxy: country.maxy,
                    opacity: 60,
                    layers: [
                        {
                            id: 'DCW_COUNTRIES',
                            name: 'Boundaries of ' + country.country,
                            style: 'quickmap-country',
                            filter: "ISO_A3='" + country.id + "'",
                            visible: false
                        },
                        {
                            id: 'GMI_LANGUAGES',
                            name: 'Languages of ' + country.country,
                            filter: "COUNTRY='" + country.id + "'",
                            visible: true
                        }
                    ]
                }));
            }
        });
    },

    makeFamilyMap: function(id){
        Ext.Ajax.request({
            url: '/families/' + id + '.json',
            scope: this,
            success: function(response,options){
                var result = Ext.decode(response.responseText);
                var family = result.data;

                this.map.zoomToBounds(family.minx, family.miny, family.maxx, family.maxy);

                this.map.addService(new LINGUIST.LLMAP.WMSService({
                    canonical_name: 'QuickMap: ' + family.family,
                    url: 'http://maggie.linguistlist.org/geoserver/wms?',
                    minx: family.minx,
                    miny: family.miny,
                    maxx: family.maxx,
                    maxy: family.maxy,
                    opacity: 60,
                    layers: [
                        {
                            id: 'GMI_FAMILY_COUNTRIES',
                            name: 'Countries of ' + family.family + ' Languages',
                            style: 'quickmap-country',
                            filter: "FAMILY='" + family.family + "'",
                            visible: false
                        },
                        {
                            id: 'GMI_LANGUAGES',
                            name: 'Languages of ' + family.family,
                            filter: "FAMILYPROP='" + family.family + "'",
                            visible: true
                        }
                    ]
                }));
            }
        });
    },

    makeLanguageMap: function(id) {
        Ext.Ajax.request({
            url: '/languages/' + id + '.json',
            scope: this,
            success: function(response, options){
                var result = Ext.decode(response.responseText);
                var lang   = result.data;

                this.map.zoomToBounds(lang.minx, lang.miny, lang.maxx, lang.maxy);

                this.map.addService(new LINGUIST.LLMAP.WMSService({
                    canonical_name: 'Quickmap: Language ' + lang.name,
                    url: 'http://maggie.linguistlist.org/geoserver/wms?',
                    minx: lang.minx,
                    miny: lang.miny,
                    maxx: lang.maxx,
                    maxy: lang.maxy,
                    opacity: 60,
                    layers: [
                        {
                            id: 'GMI_LANGUAGE_COUNTRIES',
                            name: 'Countries where ' + lang.name + ' is spoken',
                            style: 'quickmap-country',
                            filter: "LANGUAGE_CODE='" + lang.code + "'",
                            visible: false
                        },
                        {
                            id: 'GMI_LANGUAGES',
                            name: 'Where ' + lang.name + ' is spoken',
                            filter: "ISO_CODE='" + lang.code + "'",
                            visible: true
                        }
                    ]
                }));
            }
        });
    },

    zoomToCountry: function(id){
        Ext.Ajax.request({
            url: '/countries/' + id + '.json',
            scope: this,
            success: function(response, options){
                var result  = Ext.decode(response.responseText);
                var country = result.data;

                this.map.zoomToBounds(country.minx, country.miny, country.maxx, country.maxy);
            }
        });
    },

    zoomToLanguage: function(id){
        Ext.Ajax.request({
            url: '/languages/' + id + '.json',
            scope: this,
            success: function(response, options){
                var result = Ext.decode(response.responseText);
                var lang   = result.data;

                this.map.zoomToBounds(lang.minx, lang.miny, lang.maxx, lang.maxy);
            }
        });
    }
});

