/*
 * LLMAP.MapViewer Browser Panel
 * Written by Benjamin J. Cool, Joshua M. Thompson <ben,josh@linguistlist.org>
 *
 * This object class implements the map viewer as an Ext.Panel object.
 */

LINGUIST.LLMAP.MapViewer = Ext.extend(Ext.Panel, {
    constructor: function(config) {
        if (document.location.search != '') {
            var query = Ext.urlDecode(document.location.search.substr(1));

            if (query.minx != null) {
                config.search = '/services.json?' + Ext.urlEncode({
                    search: 'bbox',
                    minx: query.minx,
                    miny: query.miny,
                    maxx: query.maxx,
                    maxy: query.maxy
                });
            }
            else if (query.service != null) {
                config.initial_fs = query.service;
            }
            else if (query.language != null) {
                config.initial_language = query.language;
            }
        }

        config.layout = 'fit';
        config.items  = {
            xtype: 'map',
            defaultLonLat: { lat: 20, lon: 0 },
            defaultZoom: 2,
            enableDD: true
        };
        config.autoScroll = false;
        config.bbar   = [
            {
                text: 'Update Map',
                scope: this,
                handler: function(button) {
                    this.ovm.updateMap();
                }
            },
            '-',
            {
                text: 'Clear Map',
                scope: this,
                handler: function(button) {
                    this.map.clearMap();
                }
            },
            '-',
            {
                text: 'Help',
                scope: this,
                handler: function() {
                    this.help_window.show();
                }
            },
            '-',
            {
                id: 'toggle-layer-button',
                text: 'Toggle Layer Controls',
                scope: this,
                pressed: true,
                enableToggle: true,
                toggleGroup: 'leftbar',
                toggleHandler: function(button, pressed) {
                    if (pressed) {
                        this.west_panel.show();
                    }
                    else {
                        this.west_panel.hide();
                    }

                    this.handleResize();
                }
            },
            '-',
            {
                id: 'toggle-legend-button',
                text: 'Toggle Map Legend',
                scope: this,
                pressed: true,
                enableToggle: true,
                toggleGroup: 'rightbar',
                toggleHandler: function(button, pressed) {
                    if (pressed) {
                        this.east_panel.show();
                    }
                    else {
                        this.east_panel.hide();
                    }

                    this.handleResize();
                }
            },
/*
            '-',
            {
                id: 'toggle-identify-button',
                text: 'Identify',
                scope: this,
                pressed: false,
                enableToggle: true,
                toggleGroup: 'identify',
                toggleHandler: function(button, pressed) {
                    if (pressed) {
                        this.map.identifyOn = true;
                    }
                    else {
                        this.map.identifyOn = false;
                    }
                }
            },
*/
            '->',
            {
                text: 'Quick Map',
                scope: this,
                handler: function(button) {
                    this.quickmap.show();
                }
            },
            '-',
            {
                text: 'Find New Layers',
                menu: [
                    {
                        text: 'Add WMS layer...',
                        scope: this,
                        handler: function () {
                            var dialog = Ext.MessageBox.prompt('Add WMS Server', 'WMS server to add:', function(btn, url) {
                                if (btn == 'ok') {
                                    this.map.loadService({
                                        type: 'wms',
                                        url: url
                                    }, this.map.addService, this.map);
                                }
                            }, this);
                        }
                    },
                    {
                        text: 'Instructions',
                        scope: this,
                        handler: function () { this.wms_help_window.show(); }
                    },
                    {
                        text: 'Examples',
                        scope: this,
                        handler: function () { this.wms_examples_window.show(); }
                    }
                ]
            }
        ];

        LINGUIST.LLMAP.MapViewer.superclass.constructor.call(this, config);

        var date = new Date();

        this.cookies = new Ext.state.CookieProvider({
            expires: new Date(date.getTime()+(1000*60*60*24*180))
        });

        this.services = [];
        this.projects = [];

        this.west_panel = new Ext.Panel({
            layout: 'border',
            title: 'Layer Controls',
            autoScroll: false,
            collapsible: true,
            border: false,
            floating: true,
            width: 250,
            items: [
                {
                    region: 'center',
                    xtype: 'tabpanel',
                    activeTab: config.search == null? 0 : 1,
                    split: true,
                    border: false,
                    items: [
                        {
                            layout: 'border',
                            title: 'Available Layers',
                            items: [
                                {
                                    region: 'center',
                                    xtype: 'servicechooser',
                                    dataUrl: '/services.json'
                                },
                                {
                                    region: 'north',
                                    bodyStyle: 'padding: 5px',
                                    html: '<p style="font-size: 12px; font-weight: medium; text-align: center">To display layers, drag them to the map. </p>'
                                }
                            ]
                        },
                        {
                            title: 'Search Results',
                            xtype: 'servicechooser',
                            sortTree: true,
                            dataUrl: config.search
                        }
                    ]
                },
                {
                    region: 'south',
                    xtype: 'svcmanager',
                    title: 'Active Layers',
                    split: true,
                    height: 150,
                    listeners: {
                        scope: this,
                        checkchange: function() {
                            LINGUIST.LLMAP.Preferences.get('tip_layercheck', function() {});
                        }
                    }
                }
            ],
            listeners: {
                scope: this,
                beforecollapse: function() {
                    this.west_panel.hide();

                    Ext.getCmp('toggle-layer-button').toggle(false);

                    this.handleResize();

                    return false;
                }
            }
        });

        this.east_panel = new Ext.Panel({
            layout: 'border',
            title: 'Map Legend',
            collapsible: true,
            floating: true,
            width: 200,
            items: [
                {
                    region: 'north',
                    border: true,
                    bodyStyle: { 'padding': '5px', 'text-align': 'center' },
                    height: 30,
                    html: 'Zoom in to see labels'
                },
                {
                    region: 'center',
                    border: false,
                    autoScroll: true,
                    bodyStyle: 'padding: 10px',
                    items: { xtype: 'legend' }
                },
                {
                    region: 'south',
                    layout: 'border',
                    border: true,
                    height: 60,
                    items: [
                        {
                            region: 'north',
                            border: false,
                            bodyStyle: { 'padding': '5px', 'text-align': 'center' },
                            height: 30
                        },
                        {
                            region: 'center',
                            border: false,
                            bodyStyle: { 'padding': '5px', 'text-align': 'center' },
                            height: 30
                        }
                    ]
                }
            ],
            listeners: {
                scope: this,
                beforecollapse: function() {
                    this.east_panel.hide();

                    this.handleResize();

                    Ext.getCmp('toggle-legend-button').toggle(false);

                    return false;
                }
            }
        });

        this.chooser  = this.west_panel.getComponent(0).getComponent(0).getComponent(0);
        this.ovm      = this.west_panel.getComponent(1);
        this.map       = this.getComponent(0);
        this.quickmap = new LINGUIST.LLMAP.QuickMap({ map: this.map });
        this.legend   = this.east_panel.getComponent(1).getComponent(0);
        this.identify = new LINGUIST.LLMAP.Identify();

        /*this.identify_tabs = new Ext.TabPanel({
            region: 'center',
            activeTab: 0,
            items: [{
                title: 'temp',
                html: 'ndfjsnk',
                autoScroll: true
            }]
        });

        this.identify_nav = new Ext.Panel({
            title: 'Navigation',
            region: 'west',
            split: true,
            width: 200,
            collapsible: true
        });

        this.identify = new Ext.Window({
            title: 'Identify',
            closable: true,
            width: 600,
            height: 400,
            plain: true,
            layout: 'border',
            items: [this.identify_nav,this.identify_tabs],
            listeners:{
                scope:this,
                beforeclose: function(p){
                    p.hide();
                }
            }
        });*/

        this.wms_examples_window = new Ext.Window({
            title: 'WMS Server Examples',
            width: 600,
            height: 400,
            autoLoad: '/examples.html',
            autoScroll: true,
            bodyStyle: 'background: white; padding: 10px;',
            closable: false,
            draggable: true,
            hidden: true,
            buttons: [
                {
                    text: 'Hide',
                    scope: this,
                    handler: function() { this.wms_examples_window.hide(); }
                }
            ]
        });

        this.wms_help_window = new Ext.Window({
            title: 'WMS Server Help',
            width: 600,
            height: 400,
            autoLoad: '/instructions.html',
            autoScroll: true,
            bodyStyle: 'background: white; padding: 10px;',
            closable: false,
            draggable: true,
            hidden: true,
            buttons: [
                {
                    text: 'Hide',
                    scope: this,
                    handler: function() { this.wms_help_window.hide(); }
                }
            ]
        });

        this.help_window = new Ext.Window({
            title: 'LL-MAP Tutorial',
            width: 650,
            height: 430,
            modal:true,
            closable: false,
            draggable: true,
            hidden: true,
            items: [
                {
                    xtype: 'flash',
                    hideMode : 'offsets',
                    url: 'flvplayer.swf',
                    expressInstall: true,
                    width: 640,
                    height: 360,
                    flashParams: {
                        allowfullscreen: 'true'
                    },
                    flashVars: {
                        file: '/user-media/tutorial.mp4',
                        type: 'http',
                        autostart: 'false',
                        stretching: 'exactfit'
                    }
                }
            ],
            buttons: [
                {
                    text: 'Hide',
                    scope: this,
                    handler: function() {
                        this.help_window.hide();
                        this.help_window.content = '';
                    }
                }
            ]
        });

        var prefs = LINGUIST.LLMAP.Preferences;

        prefs.create({
            xtype: 'yesno',
            name: 'show_tutorial',
            title: 'Welcome to LL_MAP',
            text: 'Would you like to see the tutorial?'
        });

        prefs.create({
            xtype: 'showtip',
            name: 'tip_addservice',
            text: 'To adjust opacity right-click on the service name in the lower left panel and select "Set Opacity".'
        });

        prefs.create({
            xtype: 'showtip',
            name: 'tip_layercheck',
            text: 'Turning layers on or off will not take effect until you click Update Map.'
        });

        prefs.load();

        this.ovm.attach(this.map);
        this.legend.attach(this.map);

        this.on('resize', this.handleResize, this);

        this.contextMenu = new Ext.menu.Menu({
            items: [
                {
                    text: 'What is this?',
                    scope: this,
                    handler: this.handleIdentify
                }
            ]
        });

        this.map.addListener({
            addservice: function(service) {
                LINGUIST.LLMAP.Preferences.get('tip_addservice', function() {});
            },
            olclick: {
                scope: this,
                fn: function(evt) { this.contextMenu.hide(); }
            },
            olrightclick: {
                scope: this,
                fn: function(evt) {
                    this.lastClick = evt.xy;

                    this.contextMenu.showAt([ evt.clientX, evt.clientY ]);
                }
            },
            render: {
                scope: this,
                single: true,
                fn: function() {
                    this.east_panel.render(this.body);
                    this.west_panel.render(this.body);

                    var ep = this.east_panel.getComponent(2);

                    this.map.map.addControl(new OpenLayers.Control.MousePosition({
                        element: ep.getComponent(0).body.dom
                    }));
                    this.map.map.addControl(new OpenLayers.Control.Scale(ep.getComponent(1).body.dom));

                    this.handleResize(); // adjust panels to initial sizes

                    this.map.addService(new LINGUIST.LLMAP.BaseMapOverlay);

                    if (this.initialConfig.quickmap) {
                        this.quickmap.show();
                    }

                    if (this.initial_fs) {
                        this.map.loadService({ id: this.initial_fs }, function (service) {
                            var chooser = this.chooser;
                            var map     = this.map;

                            this.chooser.expandPath('/' + service.path.join('/'), 'id', function(success, lastNode) {
                                lastNode.select();

                                chooser.showServiceInfo(service);

                                map.addService(service);
                            });

                        }, this);
                    }

                    if (this.initial_language) {
                        this.quickmap.makeLanguageMap(this.initial_language);
                    }

                    this.showFirstTime();
                }
            },
            setbasemap: {
                scope: this,
                fn: this.handleResize // for some reason the controls move when the basemap changes
            }
        });
    },

    handleResize: function() {
        if (this.east_panel.rendered && this.west_panel.rendered) {
            var width  = this.getInnerWidth();
            var height = this.getInnerHeight();
            var left   = 0;
            var right  = 0;

            this.east_panel.setHeight(height);
            this.west_panel.setHeight(height);

            if (!this.east_panel.hidden) {
                right = this.east_panel.getInnerWidth() + this.east_panel.getFrameWidth();

                this.east_panel.setPosition(width - right, 0);
            }

            if (!this.west_panel.hidden) {
                left = this.west_panel.getInnerWidth() + this.west_panel.getFrameWidth();

                this.west_panel.setPosition(0, 0);
            }

            this.map.setControlOffsets(left, right, 0);
        }
    },

    handleIdentify: function() {
        var map = this.map;

        for (var i = 0 ; i < map.services.length ; i++) {
            if (!map.services[i].map_layer.isBaseLayer) {
                


				var params = {
					TITLE: map.services[i].canonical_name,
					REQUEST: "GetFeatureInfo",
					EXCEPTIONS: 'application/vnd.ogc.gml',
					CQL_FILTER: 'INCLUDE',
					BBOX: map.map.getExtent().toBBOX(),
					X: this.lastClick.x,
					Y: this.lastClick.y,
					INFO_FORMAT: 'text/html',
					LAYERS: map.services[i].map_layer.params.LAYERS,
					QUERY_LAYERS: map.services[i].map_layer.params.LAYERS,
					TRANSPARENT: 'true',
					SRS: 'EPSG:4326',
					SERVICE:'WMS',
					VERSION:'1.1.1',
					WIDTH: map.map.size.w,
					HEIGHT: map.map.size.h
				};
				
				
				Ext.applyIf(params,map.services[i].map_layer.params);


				Ext.Ajax.request({
					url: map.services[i].map_layer.url,
					params: params,
					scope: this,
					method: 'GET',
					callback: function(options,success,response){
						if ((response.status == 200) && (response.responseText.trim() != "")) {
							Ext.apply(options.params,{ title: options.params.TITLE, html: response.responseText });
							this.identify.update(options.params);
						}
					}
				});
                
            }
        }

        this.identify.show();
    },

    showFirstTime: function()  {
        LINGUIST.LLMAP.Preferences.get('show_tutorial', function(pref, value, data) {
            if (value) {
                this.help_window.show();
                this.east_panel.hide();

                Ext.getCmp('toggle-legend-button').toggle(false);

            }
        }, this);
    }
});

Ext.ComponentMgr.registerType('mapviewer', LINGUIST.LLMAP.MapViewer);
