﻿
Ext.override(Ext.grid.GridView, {
	layout : function(){
		if(!this.mainBody){
			return;         }
		var g = this.grid;
		var c = g.getGridEl();
		var csize = c.getSize(true);
		var vw = csize.width;
		if(vw < 20 || csize.height < 20){
			return;
		}
		if(g.autoHeight){
			this.scroller.dom.style.overflow = 'visible';
			this.scroller.dom.style.position = 'static';
		}else{
			this.el.setSize(csize.width, csize.height);
			var hdHeight = this.mainHd.getHeight();
			var vh = csize.height - (hdHeight);
			this.scroller.setSize(vw, vh);
			if(this.innerHd){
				this.innerHd.style.width = (vw)+'px';
			}
		}
		if(this.forceFit){
			if(this.lastViewWidth != vw){
				this.fitColumns(false, false);
				this.lastViewWidth = vw;
			}
		}else {
			this.autoExpand();
			this.syncHeaderScroll();
		}
		this.onLayout(vw, vh);
	}
});

Ext.override(Ext.Window, {
    scale: function(w, h) {
        a = Ext.lib.Anim.motion(this.el, {height: {to: h}, width: {to: w}});
        a.onTween.addListener(function(){
            if (this.fixedCenter) {
                this.center();
            }
            this.syncSize();
            this.syncShadow();
        }, this);
        a.animate();
    }
});

Ext.override(Ext.Layer, {
    setShadowVisible: function(boolean) {
        if (this.shadow) {
            if (boolean) {
                this.shadow.show();
            } else {
                this.shadow.hide();
            }
        }
    }
});

Ext.ux.SliderTip = Ext.extend(Ext.Tip, {
    minWidth: 10,
    offsets : [0, -10],
    init : function(slider){
        slider.on('dragstart', this.onSlide, this);
        slider.on('drag', this.onSlide, this);
        slider.on('dragend', this.hide, this);
        slider.on('destroy', this.destroy, this);
    },

    onSlide : function(slider){
        this.show();
        this.body.update(this.getText(slider));
        this.doAutoWidth();
        this.el.alignTo(slider.thumb, 'b-t?', this.offsets);
    },

    getText : function(slider){
        return slider.getValue();
    }
});

socioscope.explorerModule = function() {

//    var testLayer;

    var version = '2.0.0';

    var strMode;

    var strAppUrl = socioscope.appUrl;

//    var strMapservUrl = 'http://localhost';
//    var strMapservExeName = 'mapserv.exe';

    var strMapservUrl = strAppUrl + 'wms/';
    var strMapservExeName = '';
    
    var strSldUrl = strAppUrl + 'wms/sld.ashx';
    
    var strAppName = socioscope.appName; 
    
    var mapHistory;

    var remainingLayersToLoad = 0;

    var mapMaxExtent = new OpenLayers.Bounds(265561, 5027556, 308620, 5064251);
    var googleMaxExtent = new OpenLayers.Bounds(-8244344,5679271,-8160264,5740420);
    
    var useGoogle = true;

    var strMapProjection = 'epsg:2145'; // ou EPSG:32188
    var strGoogleMapProjection = 'epsg:900913';  // ou EPSG:3785  
    
    var strMapOutputFormat = 'png';
    var strLegendOutputFormat = 'png2';
    
    var mapMaxResolution = 200;
    var mapUnits = 'meters';
    
    var themeLayerOpacity = 0.7;

    var strBaseMapServiceName = 'fondcarte';
    var strBaseMapServiceDescription = 'Carte de base';
    var strBaseMapLayers = 'fleuve,rmr,arrondissements';
    
    var strThemeMapServiceDescription = 'Thématique';
    
    var strLimitsMapServiceName = 'limites';
    var strLimitsMapServiceDescription = 'Limites';
    var strLimitsMapLayers = 'limitesarrondissements';
    
    var strGoogleMapType = 'G_PHYSICAL_MAP';
    
    var zoomFullExtentOnVariableSwitch = false;
    
    var iIndicatorId = 0;
    var iVariableId;
    var objVariable;
    var idObjectif = 0;
    
    var mainApplicationWindow;
    var selectionWindow;
    var selectionPanel;

    var mapWidget;
    var tableWidget;
    var tablePager;
    
    var viewAllIndicators;
    var viewAllObjectives;
    var viewAllParcours;
    var storeDescriptionIndicateur;
    var viewVariables;
    var storeVariables;
    var comboVariables;
    var storeUpstreamIndicators;
    var viewUpstreamIndicators;
    var storeDownstreamIndicators;
    var viewDownstreamIndicators;
    var storeLocations;
    
    var historyTokenDelimiter = '|';
               
    storeDescriptionIndicateur = new Ext.data.Store({
        url: strAppUrl + 'services/api.ashx',
        reader: new Ext.data.XmlReader({
            record: 'indicateur',
            id: 'id_indicateur'
            }, ['id_indicateur', 'nom_indicateur', 'description_indicateur', 'type']
        ),
        baseParams: {method: 'indicator.getDescription'}
    });
    
    storeDescriptionIndicateur.on('beforeload', function(store, options) {
        Ext.getCmp('panel_description_indicateur').body.mask(Ext.UpdateManager.defaults.indicatorText);
//        Ext.getCmp('panel_description_indicateur').getBottomToolbar().showBusy('Un instant...');
    }, this);
     
    storeDescriptionIndicateur.on('load', function(store, records, options) {
        
        var record = records[0];
        
        strMode = record.get('type') == 'indicateur' ? 'indic' : 'profil';
        Ext.getCmp('relationsPanel').setVisible(strMode == 'indic');
        
        Ext.getCmp('panel_description_indicateur').body.update(record.get('description_indicateur').replace('/(\r\n|[\r\n])/g', '<br/><br/>')).highlight().unmask();
        Ext.get('page_title').update(record.get('nom_indicateur')).highlight();
        document.title = strAppName + ' - ' + record.get('nom_indicateur');   
        
    }, this);
    
    storeVariables = new Ext.data.GroupingStore({
        url: strAppUrl + 'services/api.ashx',
        reader: new Ext.data.XmlReader({
            record: 'variable',
            id: 'id_variable'
            }, ['id_variable', 'nom_variable', 'table']
        ),
//        groupField: 'table',
        sortInfo: {field: 'nom_variable', direction: "ASC"},
        baseParams: {method: 'indicator.getVariables'}
    });
    
    storeVariables.on('load', function(store, records, options) { 
    
        if (records.length === 0) {
        
            switchVariable(null);
            Ext.getCmp('variablesCombo').disable();
            
            Ext.getCmp('dataPanel').setTitle('Aucune variable n\'est présentement disponible pour cet ' + (strMode == 'indic' ? 'indicateur' : 'élément de profil') + '...');
            Ext.getCmp('variablesCombo').hide();
        
        } else {

            Ext.getCmp('dataPanel').setTitle('Nombre de variable(s) illustrant cet ' + (strMode == 'indic' ? 'indicateur' : 'élément du profil') + ' : ' + records.length);

            Ext.getCmp('variablesCombo').enable().setValue('');
            Ext.getCmp('variablesCombo').show();

        }
    
    }, this);

    storeLocations = new Ext.data.Store({
        url: strAppUrl + 'services/api.ashx',
        reader: new Ext.data.XmlReader({
            record: 'lieu',
            id: 'nom_lieu'
            }, ['nom_lieu', 'type', (useGoogle ? 'bounds' : 'bounds')]
        ),
        baseParams: {method: 'socioscope.getLocations', like: ''}
    });
            
    var handleHistoryChange = function(token) {
    
        if (token !== ''){
        
            var parts = token.split(historyTokenDelimiter);
            
            if (parts[0]) {
                switchIndicator(parts[0].split('=')[1]);
            }

        }
    
    };
    
    var mapTip;
    var mapTipTimeout;
    
    var updateMapTip = function(store, fields) {
    
        if (mapTipTimeout) {
            clearTimeout(mapTipTimeout);
        }
    
        var height = mapTip.getEl().getHeight();
        var position = mapTip.getEl().getXY();
        
        var str = '<h4>Résultat</h4>';
        
        Ext.each(fields, function(obj, index, all) {
            str += (Ext.DomQuery.selectValue(obj, store.reader.xmlData) == null ? '' : Ext.DomQuery.selectValue(obj, store.reader.xmlData)) + '<br/>';
        }, this)
        
//        var node = Ext.DomQuery.selectNode('MTLNOM')
        
        if (str !== '') {
            mapTip.show();
            mapTip.body.update(str);
            mapTip.syncSize();
        } else {
            mapTip.body.update('Aucun résultat...');
        }
        
        var hide = function() {
            mapTip.hide();
        }
        
        mapTipTimeout = hide.defer(5000);
        
//        mapTip.setPagePosition(position[0], position[1] - (mapTip.getEl().getHeight() - height));

    };
    
    var cancelMapClick = function() {
        try {
            mapTip.hide();
        } catch(e) {
        }
    }

    var handleMapClick = function(e) {
    
        try {
    
            if (!mapTip) {
                mapTip = new Ext.Tip({html: 'Infos', shadow: 'frame', shadowOffset: 8, trackMouse: false, width: 150, autoHeight: true});
                mapTip.showAt([0,0]);
            }
            
            var offset = Ext.fly('mapwidget').getXY();
            
            mapTip.show();
            mapTip.body.update('<div class="loading">Un instant...</div>');
            mapTip.setPagePosition(e.xy.x + offset[0] - mapTip.getEl().getWidth() - 5, e.xy.y + offset[1]);

            var layer;
                 
            var x = e.xy.x;
            var y = e.xy.y;
            
            var lonlat = mapWidget.getLonLatFromViewPortPx(e.xy);
            
            layer = mapWidget.getLayer('thematique');
                          
            if (layer) {
                            
    //            var strUrl = layer.getURL(mapWidget.getExtent()).replace(/getMap/i, 'getFeatureInfo');
                var strUrl = strAppUrl;
                            
                var bounds = layer.getExtent();
                var ms = mapWidget.getCurrentSize();
                
    //            strUrl += '/wms' + strMapservExeName + '?map=' + iVariableId + '&service=WMS&VERSION=1.1.0&LAYERS=' + iVariableId + '&REQUEST=GetFeatureInfo&FORMAT=png&WIDTH=' + ms.w + '&HEIGHT=' + ms.h + '&SRS=' + strMapProjection + '&BBOX=' + bounds.toBBOX();
                strUrl += 'services/getfeatureinfo.ashx?map=' + iVariableId + '&service=WMS&VERSION=1.1.0&LAYERS=' + iVariableId + '&REQUEST=GetFeatureInfo&FORMAT=png&WIDTH=' + ms.w + '&HEIGHT=' + ms.h + '&SRS=' + strMapProjection + '&BBOX=' + bounds.toBBOX();
                strUrl += '&x=' + x + '&y=' + y + '&QUERY_LAYERS=' + iVariableId + '&INFO_FORMAT=gml';      
                
                    var xmlReader = new Ext.data.XmlReader({
                        record: iVariableId + '_feature',   
                        id: Ext.DomQuery.selectValue('keydescfield', objVariable)
                        }, [Ext.DomQuery.selectValue('keyfield', objVariable), Ext.DomQuery.selectValue('keydescfield', objVariable)]  
                    );
                    
                    var dataStore = new Ext.data.Store({
                        url: strUrl,
                        reader: xmlReader
                    });
                    
                    dataStore.on('load', function(store, records, options) {
                        if (store.getTotalCount() > 0) {
                            updateMapTip(store, new Array(Ext.DomQuery.selectValue('keydescfield', objVariable), Ext.DomQuery.selectValue('valuefield', objVariable)));
                        } else {
                            mapTip.body.update('Aucun résultat...');
                        }
                    });
                    
                    dataStore.load();       
            }
        
        } catch(e) {
            logMessage(e);
        }
    
    };
    
    var registerMapLayer = function(evt) {
    
        logMessage('Adding layer ' + evt.layer.id + ' to map...');

        var layer = evt.layer;
        
        layer.events.register("loadstart", layer, function() {
            remainingLayersToLoad = remainingLayersToLoad + 1;
            displayMapLayersProgress();
        });
        
        layer.events.register("loadend", layer, function() {
            remainingLayersToLoad = remainingLayersToLoad - 1;
            displayMapLayersProgress();
        });
     
    };
    
    var toggleMapLayer = function(layerName, visible) {
    
        try {
            var layer = mapWidget.getLayer(layerName);
            layer.setVisibility(visible);
        } catch(e) {
        
        }
    
    };
    
    var displayMapLayersProgress = function() {
        
        if (remainingLayersToLoad > 0) {
            Ext.getCmp('mapWidgetStatusbar').showBusy('Affichage de la carte : ' + remainingLayersToLoad + ' couche(s) restante(s)...');
        } else {
            Ext.getCmp('mapWidgetStatusbar').clearStatus();
        }
            
    };
    
    var updateMapPanel = function(variableObj) {
    
        if (mapWidget) {
            setupMap(variableObj);
        } else {
            logMessage('Loading Google Maps API...');
            google.load("maps", "2", {language: 'fr', nocss: true, callback: setupMap.createDelegate(this, [variableObj])});
        }
        
    };
    
    var updateLegend = function(variableObj) {
    
        logMessage('Updating legend...');
        
        if (variableObj) {
        
            var variableId = Ext.DomQuery.selectValue('id_variable', variableObj);
            var variableName = Ext.DomQuery.selectValue('nom_variable', variableObj);
            
            Ext.getCmp('legendPanel').show();
            
            var strUrl = strMapservUrl + strMapservExeName + '?map=' + variableId + '&mode=legend&layers=' + variableId;  
            Ext.fly('themeLegend').update('<p>' + variableName + '</p><img src="' + strUrl + '"/>');
  
        } else {
        
            Ext.getCmp('legendPanel').hide();
        
        }
    
    };
    
    var setupMap = function(variableObj) {
    
        var firstRun;
        var layer;
        
        var variable_id = iVariableId;
    
        logMessage('Updating map...');
        
        cancelMapClick();
         
        if (variable_id) {
        
            if (mapWidget) {
        
                firstRun = false;

                try {
                    mapWidget.removePopup(infoPopup);
                    cbLegendeGoogle.setValue(true);
                } catch(err) {
                
                }
                
                layer = mapWidget.getLayer('thematique');

                if (layer) {
                    mapWidget.removeLayer(layer);
                }
                
                layer = mapWidget.getLayer('selection');
                  
                if (layer) {
                    layer.setVisibility(false);
                    mapWidget.removeLayer(layer);
                }
                  
            } else {
        
                logMessage('Creating map widget...');
                
                firstRun = true;
            
                var navigationControl = new OpenLayers.Control.Navigation({zoomWheelEnabled: false});
                
                OpenLayers.Control.Hover = OpenLayers.Class(OpenLayers.Control, {   
                        
                    defaultHandlerOptions: {
                        'delay': 2000,
                        'pixelTolerance': 3,
                        'stopMove': false
                    },
     
                    initialize: function(options) {
                                        
                        this.handlerOptions = OpenLayers.Util.extend(
                            {}, this.defaultHandlerOptions
                        );
                        OpenLayers.Control.prototype.initialize.apply(
                            this, arguments
                        ); 
                        this.handler = new OpenLayers.Handler.Hover(
                            this,
                            {'pause': this.onPause, 'move': this.onMove},
                            this.handlerOptions
                        );
                        
                    }, 
     
                    onPause: function(e) {
                        handleMapClick(e);
                    },
     
                    onMove: function(e) {
                        cancelMapClick();
                    }
                    
                });
                
                var hoverControl = new OpenLayers.Control.Hover({
                    handlerOptions: {
                        'delay': 500,
                        'pixelTolerance': 2
                    }
                });
                          
                var mapHistoryControl = new OpenLayers.Control.NavigationHistory();
                
                mapHistory = mapHistoryControl;
                
                var options = {
                    projection: new OpenLayers.Projection('EPSG:900913'),
                    units: 'm',
                    maxExtent: mapMaxExtent,
                    restrictedExtent: mapMaxExtent,
                    controls: [navigationControl, hoverControl, mapHistoryControl]
                };
                
                mapWidget = new OpenLayers.Map('mapwidget', options);
                
                mapWidget.events.register('preaddlayer', mapWidget, registerMapLayer.createDelegate(this));
                
//                mapWidget.addControl(new OpenLayers.Control.MousePosition({displayProjection: new OpenLayers.Projection('EPSG:4326')}));
//                hoverControl.activate();
      
                if (useGoogle) {
                
                    layer = new OpenLayers.Layer.Google('Google', {sphericalMercator: true, type: G_PHYSICAL_MAP});
                    layer.id = 'google_phys';
                    mapWidget.addLayer(layer);

                } 
                      
                layer = new OpenLayers.Layer.WMS(strLimitsMapServiceDescription, strMapservUrl + strMapservExeName, {map: strLimitsMapServiceName, version: '1.1.0', layers: strLimitsMapLayers, format: strMapOutputFormat}, {singleTile: true, isBaseLayer: false, isplayOutsideMaxExtent: true, displayInLayerSwitcher: false, ratio: 2});
                layer.id = 'limites';
                layer.setVisibility(false);
                layer.setOpacity(themeLayerOpacity);
                mapWidget.addLayer(layer);
                
                mapWidget.events.register('click', null, handleMapClick.createDelegate(this));
                mapWidget.events.register('dragstart', null, cancelMapClick.createDelegate(this));
                mapWidget.events.register('move', null, cancelMapClick.createDelegate(this));
                   
            }

            Ext.getCmp('mapWidgetPanel').enable();
                            
            layer = new OpenLayers.Layer.MapServer(strThemeMapServiceDescription, strMapservUrl + strMapservExeName, {map: variable_id, mode: 'map', layers: variable_id, map_imagetype: strMapOutputFormat}, {reproject: false, singleTile: true, isBaseLayer: false, ratio: 1.5, transitionEffect: 'none'});
            layer.id = 'thematique';
            layer.setOpacity(useGoogle ? themeLayerOpacity : 0);
            mapWidget.addLayer(layer);
            
//            Ext.getCmp('sliderMapThemeTransparency').setValue(themeLayerOpacity * 100);
            
            layer = mapWidget.getLayer('limites');
            
            if (layer) {
                mapWidget.raiseLayer(layer, 1);
            }
               
            layer = new OpenLayers.Layer.WMS('Sélection', strMapservUrl + strMapservExeName, {map: variable_id, version: '1.1.0', layers: variable_id, format: strMapOutputFormat}, {singleTile: true, isBaseLayer: false, ratio: 2});           
            layer.id = 'selection';
            layer.setOpacity(1.0);
            layer.displayInLayerSwitcher = false;
            layer.setVisibility(false);
            mapWidget.addLayer(layer);
            mapWidget.raiseLayer(layer, -1);

            updateLegend(variableObj);
     
            if (!firstRun) {
                if (zoomFullExtentOnVariableSwitch) {
                    mapWidget.zoomTo(10);
                }
            } else {
                mapWidget.zoomTo(10);
            }
                   
        } else {
        
            if (mapWidget) {
            
                layer = mapWidget.getLayer('thematique');
                
                if (layer) {
                    layer.setVisibility(false);
                }
                
            }
        
            Ext.getCmp('mapWidgetPanel').disable();
            updateLegend(null);
        
        }
                                             
    };
    
    var hiliteFeaturesOnMap = function(layerName, item, id) {
        
        var layer;
        
        layer = mapWidget.getLayer('selection');
        layer.mergeNewParams({sld: strSldUrl + '?layername=' + layerName + '&propertyname=' + item + '&literal=' + id});
        layer.setVisibility(true);
               
    };
    
    var clearMapHilite = function() {
        mapWidget.getLayer('selection').setVisibility(false);
    };
    
    var switchIndicator = function(id) {
   
        if (id != iIndicatorId) {
                
            logMessage('Switching to indicator ' + id);
            iIndicatorId = id;
        
            storeDescriptionIndicateur.load({params: {indicator_id: id}});
            storeVariables.load({params: {indicator_id: id}});
                      
            storeUpstreamIndicators.load({params: {indicator_id: id}});
            viewDownstreamIndicators.store.load({params: {indicator_id: id}});  
            
            switchVariable(null);
        
        }
           
    };
    
    var rowClickHandler = function(grid, rowIndex, e) {
    
        logMessage('Handling row selection...');
    
//      this.clearPopups();
    
        var cm = grid.getColumnModel();
        var idField = cm.getDataIndex(1); 
        
        var selection = grid.getSelectionModel().getSelections();
        var record = selection[0];
        
        if (record) {
        
            var bbox = OpenLayers.Bounds.fromString(record.get('bbox'));
            var bbox2 = bbox.transform(new OpenLayers.Projection('EPSG:32188'), new OpenLayers.Projection('EPSG:900913'));
            
            mapWidget.zoomToExtent(bbox2);
            
            var layer = mapWidget.getLayer('selection');
            
            var params = {};
            params.hilite_item = idField;
            
            var hiliteId = '';
            
            var keyField = Ext.DomQuery.selectValue('keyfield', objVariable);

            hiliteFeaturesOnMap(iVariableId, keyField, record.get(idField));
            
        } else {

            clearMapHilite();
            
        }
        
    };
    
    
    var updateTablePanel = function(variableObj) {
        
        if (variableObj) {
                   
            if (tableWidget) {
                tableWidget.enable();
            }
            
            try {
            
                var keyField = Ext.DomQuery.selectValue('keyfield', variableObj);
                var keyDescField = Ext.DomQuery.selectValue('keydescfield', variableObj);
                var valueField = Ext.DomQuery.selectValue('valuefield', variableObj);
                
                var schemaObj = Ext.DomQuery.selectNode('schema', variableObj);
                     
                var arrFields = [];
                var arrColumns = [];
                var objColumn;
                
                arrFields[0] = keyField;
                arrFields[1] = keyDescField;
                arrFields[2] = valueField;
                
                var fieldObj;

                objColumn = {};
                objColumn.header = '';
                objColumn.dataIndex = 'row_id';
                objColumn.width = 50;
                objColumn.fixed = true;
                
                arrColumns[0] = objColumn;
                
                fieldObj = Ext.DomQuery.selectNode('keyfield', schemaObj);

                objColumn = {};  
                objColumn.header = fieldObj.getAttribute('alias');
                objColumn.dataIndex = keyField;
                objColumn.width = 100;
                objColumn.tooltip = fieldObj.getAttribute('description');

                arrColumns[1] = objColumn;
                
                fieldObj = Ext.DomQuery.selectNode('keydescfield', schemaObj);

                objColumn = {};  
                objColumn.header = fieldObj.getAttribute('alias');
                objColumn.dataIndex = keyDescField;
                objColumn.tooltip = fieldObj.getAttribute('description');

                arrColumns[2] = objColumn;
                
                fieldObj = Ext.DomQuery.selectNode('valuefield', schemaObj);
                
                objColumn = {};
                objColumn.header = fieldObj.getAttribute('alias');
                objColumn.dataIndex = valueField;
                objColumn.align = 'right';
                objColumn.width = 150;
                objColumn.tooltip = fieldObj.getAttribute('description');

                arrColumns[3] = objColumn;
                
                objColumn = {};
                objColumn.header = '';
                objColumn.hidden = true;
                objColumn.dataIndex = 'bbox';

                arrColumns[4] = objColumn;
                          
                var store = new Ext.data.Store({
                
                    url: strAppUrl + 'services/api.ashx',
                    remoteSort: true,
                    baseParams: {method: 'variable.getTable', variable_id: iVariableId},
                    reader: new Ext.data.XmlReader({
                           record: 'row',
                           totalRecords: 'total',
                           id: keyField
                       }, [
                           'row_id', keyField, keyDescField, valueField, 'bbox'
                       ])
                });
              
                var cm = new Ext.grid.ColumnModel(arrColumns);
                cm.defaultSortable = true;
                
                var sm = new Ext.grid.RowSelectionModel({singleSelect: true});
                
                if (tableWidget) {
                
                    tableWidget.reconfigure(store, cm);
                
                } else {
                                            
                    tableWidget = new Ext.grid.GridPanel({
                        store: store,
                        cm: cm,
                        sm: sm,
                        enableColumnMove: false,
                        enableColumnHide: false,
                        trackMouseOver: true,
                        collapsible: false,
                        applyTo: 'tablewidget',
                        autoHeight: true,
                        frame: true,
                        loadMask: {msg: '&nbsp;', msgCls: 'nothing'},
                        bbar: tablePager = new Ext.PagingToolbar({
                            store: store,
                            pageSize: 15,
                            displayInfo: true
                        }),
                        enableHdMenu: false,
                        hideMode: 'visibility',
                        autoExpandColumn: 2
                    });
                                  
                    tableWidget.on('rowclick', rowClickHandler, this);

                }

                tablePager.bind(store);
                    
                store.setDefaultSort(arrFields[0], 'ASC');
                store.load({params: {start: 0, limit: 15}});
            
            } catch(e) {
            
            }
             
        } else {
        
            if (tableWidget) {
                tableWidget.disable();
            }
            
        }
        

    };
    
    var updateSourcePanel = function(variableObj) {
    
        if (variableObj) {
        
            var sourcesArray = Ext.DomQuery.select('source', variableObj);
            
            if (sourcesArray.length > 0) {
            
                var sources = [];
                
                Ext.each(sourcesArray, function(item, index, items) {
                   
                    var source = [];
                                      
                    source.nom_source = Ext.DomQuery.selectValue('nom_source', item) === null ? '' : Ext.DomQuery.selectValue('nom_source', item);
                    source.siteweb = Ext.DomQuery.selectValue('siteweb', item) === null ? '' : Ext.DomQuery.selectValue('siteweb', item);
                    source.emetteur = Ext.DomQuery.selectValue('emetteur', item);
                    
                    sources[sources.length] = source;
                
                }, this);
               
                var tpl = new Ext.XTemplate(
                    '<h5>Source(s) :</h5>',
                    '<ul>',
                    '<tpl for=".">',
                        '<tpl if="siteweb != \'\'">',
                            '<tpl if="nom_source == \'\'">',
                                '<li><a href="{siteweb}">{emetteur}</a></li>',
                            '</tpl>',
                            '<tpl if="nom_source != \'\'">',
                                '<li><a href="{siteweb}">{emetteur}</a>, {nom_source}</li>',
                            '</tpl>',
                        '</tpl>',
                        '<tpl if="siteweb == \'\'">',
                            '<tpl if="nom_source == \'\'">',
                                '<li>{emetteur}</li>',
                            '</tpl>',
                            '<tpl if="nom_source != \'\'">',
                                '<li>{emetteur}, {nom_source}</li>',
                            '</tpl>',
                        '</tpl>',
                    '</tpl>',
                    '</ul>'
                );
                
                tpl.overwrite(Ext.getCmp('metadataPanel').body, sources);
            
            } else {
            
                Ext.getCmp('metadataPanel').body.update('');
            
            }
            
        } else {
        
            Ext.getCmp('metadataPanel').body.update('');
   
        }
    
    };
    
    var updateDataPanel = function(variableObj) {
    
        logMessage('Updating data panel...');
           
        updateMapPanel(variableObj);
        updateTablePanel(variableObj);
        updateSourcePanel(variableObj);
        
    };
    
    var switchVariable = function(variable_id) {
    
        if (variable_id != iVariableId) {
        
            if (variable_id) {
    
                logMessage('Switching to variable ' + variable_id);
                
                var xmlReader = new Ext.data.XmlReader({
                    record: 'variable',
                    id: 'id_variable'        
                }, 
                ['id_variable', 'nom_variable', 'table', 'keyfield', 'keydescfield', 'valuefield', 'ismappable']
                );
                
                var dataStore = new Ext.data.Store({
                    url: strAppUrl + 'services/api.ashx',
                    reader: xmlReader,
                    baseParams: {method: 'variable.getDescription'}
                });
                
                dataStore.on('load', function(store, records, options) {
                
                        objVariable = Ext.DomQuery.selectNode('variables/variable', store.reader.xmlData);
                        iVariableId = Ext.DomQuery.selectValue('id_variable', objVariable);
                        updateDataPanel(objVariable);
                        
                    }
                );
                
                dataStore.load({params: {variable_id: variable_id},
                    callback: function(records, options, success) {}
                });
                
            } else {
            
                iVariableId = null;
                objVariable = null;
                updateDataPanel(null);
            
            }
            
        } else {
    
            iVariableId = null;
            objVariable = null;
            updateDataPanel(null);
        
        }
                               
    };
    
    return {
       
        printHandler: function() {
        
            logMessage('Printing from explorer module...');
            
            var options = '';
            
            if (iIndicatorId) {
            
                options = options + "indicator=" + iIndicatorId; 
                
                if (iVariableId) {
            
                    options = options + "&variable=" + iVariableId;
                    options = options + "&size=" + mapWidget.getSize().w + ',' + mapWidget.getSize().h;
                    options = options + "&mapextent=" + mapWidget.getExtent().toBBOX(0);
                    
                    var mapCenter = mapWidget.getCenter().clone();
                    
                    mapCenter.transform(
                        new OpenLayers.Projection('EPSG:900913'), new OpenLayers.Projection('EPSG:4326')
                    );
                    
                    options = options + "&mapllcenter=" + mapCenter.lat + "," + mapCenter.lon;
                    options = options + "&zoom=" + mapWidget.getZoom(); 
                }
                
                var site = strAppUrl + 'services/impression.aspx?' + options;
                window.open(site,'Impression','scrollbars=yes,menubar=yes,height=600,width=800,resizable=no,toolbar=no,location=no,status=yes');
  
                      
            }
            
            return false;
            
        },
                
        init: function() {
        
            // Pour s'assurer que les fameuses cartes "roses" ne s'affichent pas...
            OpenLayers.Util.onImageLoadErrorColor = "transparent";
            OpenLayers.IMAGE_RELOAD_ATTEMPTS = 5;
        
            Ext.QuickTips.init();
            Ext.History.init();
            
            Ext.WindowMgr.zseed = 25000;
            
            Ext.Ajax.method = 'GET';
      
            Ext.BLANK_IMAGE_URL = strAppUrl + 'img/blank.gif';
            
            Ext.form.BasicForm.prototype.method = 'GET';
            Ext.form.FieldSet.prototype.autoHeight = true;
            Ext.form.FieldSet.prototype.anchor = '100%';
            
            Ext.form.Field.prototype.msgTarget = 'under';
            Ext.form.Field.prototype.anchor = '100%';
            Ext.form.Field.prototype.validationEvent = 'blur';
            
            Ext.form.TextField.prototype.blankText = socioscope.defaultFieldBlankText;
            
            // Insures that combo dropdown list is over everything, except Windows...
            Ext.form.ComboBox.prototype.listClass = 'combolist';

            Ext.layout.FormLayout.prototype.labelSeparator = ' :';
            
            Ext.StatusBar.prototype.defaultText = '';
            
            Ext.UpdateManager.defaults.indicatorText = '';
            
            Ext.Panel.prototype.titleCollapse = false;
            Ext.Panel.prototype.hideCollapseTool = false;
            Ext.Panel.prototype.border = true;
            
            Ext.Component.prototype.disabledClass = 'x-item-disabled';
  
            // TODO : transférer en CSS
            Ext.Panel.prototype.bodyStyle = "padding: 5px 5px 5px 5px;";
            Ext.form.FormPanel.prototype.bodyStyle = 'padding: 10px 10px 0px 10px;';

            Ext.PagingToolbar.prototype.displayMsg = 'Rangées {0} à {1} de {2}';
            Ext.PagingToolbar.prototype.emptyMsg = 'Pas de données';
                 
            stateProvider = new Ext.state.CookieProvider();
            Ext.state.Manager.setProvider(stateProvider);

            if (Ext.isIE6) {
                strMapOutputFormat = 'gif';
            }
            
            if (useGoogle) {
                mapMaxExtent = googleMaxExtent;
                strMapProjection = strGoogleMapProjection;
            }
              
            mainApplicationWindow = new Ext.Panel({
                frame: false,
                border: false,
                applyTo: 'conteneur_donnees',
                plugins: new Ext.ux.PanelBlind({
                items: [

                        selectionPanel = new Ext.Panel({
                            frame: true,
                            border: true,
                            autoHeight: false,
                            title: 'Veuillez sélectionner un indicateur ou un élément du profil socio-démographique :',
                            height: 400,
                            hideMode: 'visibility',
                            applyTo: 'selectionPanel',
                            buttonAlign: 'right',
                            layout: 'fit',
                            items: [
                                new Ext.TabPanel({
                                    id: 'selectionTabPanel',
                                    activeItem: 0,
                                    deferredRender: false,
                                    border: false,
                                    items: [
                                            {xtype: 'panel', autoHeight: false, title: 'Parmi la liste complète', border: false, autoScroll: true, items: [
                                                    viewAllIndicators = new Ext.DataView({
                                                        tpl: new Ext.XTemplate(
                                                            '<div><h3>Indicateurs (bleu) et <span style="color: #9C0;">éléments du profil socio-démographique (vert)</span> :</h3>',
                                                                '<ul>',
                                                                    '<tpl for=".">',
                                                                                   
                                                                        '<tpl if="nb_variables == 0">',
                                                                            '<li><a href="" rel="{id_indicateur}" class="{type}">{nom_indicateur}</a><span style="color: gray;"> : <i>aucune variable</i></span></li>',
                                                                        '</tpl>',
                                                                        '<tpl if="nb_variables == 1">',
                                                                            '<li><a href="" rel="{id_indicateur}" class="{type}">{nom_indicateur}</a><span style="color: gray;"> : 1 variable</span></li>',
                                                                        '</tpl>',
                                                                        '<tpl if="nb_variables &gt; 1">',
                                                                            '<li><a href="" rel="{id_indicateur}" class="{type}">{nom_indicateur}</a><span style="color: gray;"> : {nb_variables} variables</span></li>',
                                                                        '</tpl>',
                                                                    
                                                                    '</tpl>',
                                                                '</ul>',
                                                            '</div>'
                                                        ),       
                                                        autoHeight: true,
                                                        singleSelect: true,
                                                        selectedClass: 'none',
                                                        itemSelector: 'a',
                                                        store: new Ext.data.Store({
                                                            url: strAppUrl + 'services/api.ashx',
                                                            reader: new Ext.data.XmlReader({
                                                                record: 'indicateur',
                                                                id: 'id_indicateur'
                                                                }, ['id_indicateur', 'nom_indicateur', 'type', 'nb_variables']
                                                            ),
                                                            baseParams: {method: 'socioscope.getIndicators'}
                                                        })
                                                    })
                                                ]
                                            },
                                            {xtype: 'panel', layout: 'column', title: 'Par objectif', bodyStyle: 'padding: 0px;', items: [
                                                    {xtype: 'panel', height: 306, columnWidth: 0.5, border: false, autoScroll: true, items: [
                                                            viewAllObjectives = new Ext.DataView({
                                                                tpl: new Ext.XTemplate(
                                                                    '<div><h3>Objectifs :</h3>','<ul>','<tpl for=".">','<li><a href="" rel="{id_objectif}">{nom_objectif}</a></li>','</tpl>','</ul>','</div>'
                                                                ),
                                                                autoHeight: true,
                                                                singleSelect: true,
                                                                selectedClass: 's-selected',
                                                                itemSelector: 'a',
                                                                store: new Ext.data.Store({
                                                                    url: strAppUrl + 'services/api.ashx',
                                                                    reader: new Ext.data.XmlReader({
                                                                        record: 'objectif',
                                                                        id: 'id_objectif'
                                                                        }, ['id_objectif', 'nom_objectif']
                                                                    ),
                                                                    baseParams: {method: 'socioscope.getObjectives'}
                                                                })
                                                            })
                                                        ]
                                                    },
                                                    {xtype: 'panel', height: 306, columnWidth: 0.5, border: false, autoScroll: true, items: [
                                                    
                                                            viewIndicatorsForObjective = new Ext.DataView({
                                                                tpl: new Ext.XTemplate('<div style="padding-left: 10px;"><h3>Indicateurs associés à l\'objectif sélectionné :</h3>','<ul>','<tpl for=".">','<li><a href="" rel="{id_indicateur}">{nom_indicateur}</a></li>','</tpl>','</ul>','</div>'),
                                                                autoHeight: true,
                                                                singleSelect: true,
                                                                selectedClass: 'none',
                                                                itemSelector: 'a',
                                                                store: new Ext.data.Store({
                                                                    url: strAppUrl + 'services/api.ashx',
                                                                    reader: new Ext.data.XmlReader({
                                                                        record: 'indicateur',
                                                                        id: 'id_indicateur'
                                                                        }, ['id_indicateur', 'nom_indicateur']
                                                                    ),
                                                                    baseParams: {method: 'objective.getIndicators'}
                                                                })
                                                            })                          
                                                    
                                                        ]
                                                    }
                                                ]
                                            },
                                            {xtype: 'panel', layout: 'column', title: 'Via les parcours de vie', bodyStyle: 'padding: 0px;', items: [
                                                    {xtype: 'panel', height: 306, columnWidth: 0.5, border: false, autoScroll: true, items: [

                                                            viewAllParcours = new Ext.DataView({
                                                                tpl: new Ext.XTemplate('<div><h3>Parcours de vie :</h3>','<ul>','<tpl for=".">','<li><a href="{id}" rel="{id_parcours}">{nom_parcours} : {description}</a></li>','</tpl>','</ul>','</div>'),
                                                                autoHeight: true, 
                                                                singleSelect: true,
                                                                selectedClass: 's-selected',
                                                                itemSelector: 'a',
                                                                store: new Ext.data.Store({
                                                                    url: strAppUrl + 'services/api.ashx',
                                                                    reader: new Ext.data.XmlReader({
                                                                        record: 'parcours',
                                                                        id: 'id_parcours'
                                                                        }, ['id_parcours', 'nom_parcours', 'description']
                                                                    ),
                                                                    baseParams: {method: 'socioscope.getParcours'}
                                                                })
                                                            })
                                                       
                                                        ]     
                                                    },
                                                    {xtype: 'panel', id: 'description_parcours', height: 306, columnWidth: 0.5, border: false, autoScroll: true, bodyStyle: 'padding-right: 10px;'}
                                                ]
                                            }
            //                                {xtype: 'panel', title: 'Parmi vos favoris'}
                                        ]
            //                        bbar: new Ext.Toolbar({
            //                            items: [
            //                                'Filtrer la liste :',
            //                                {xtype: 'trigger', minLength: 3, validateOnBlur: false, width: 200, emptyText: 'Minimum 3 caractères...', triggerClass: 'x-form-clear-trigger', onTriggerClick: function() {this.setValue(''); viewAllIndicators.store.clearFilter();} }                            ]
            //                        
            //                         })
                                    
                                })

                            ]

                        })
                        
			        ]
                }),
                
                
                id: 'dataContainer',
                layout: 'anchor',

                autoHeight: true,
                items: [
                    {xtype: 'panel', frame: true, border: true, autoHeight: true, collapsible: true, cls: 'panel', title: 'Description', id: 'panel_description_indicateur', applyTo: 'panel_description_indicateur'},
                    {xtype: 'panel', frame: true, border: true, layout: 'column', autoHeight: true, collapsible: true, cls: 'panel', title: 'Relations avec les autres indicateurs', id: 'relationsPanel', applyTo: 'relationsPanel', items: [
                            {xtype: 'panel', border: true, columnWidth: 0.5, autoHeight: true, id: 'panel_amont', applyTo: 'panel_amont', items: [
                            
                            
                                    viewUpstreamIndicators = new Ext.DataView({
                                        tpl: new Ext.XTemplate('<div><h5>L\'indicateur peut être influencé par :</h5><ul>','<tpl for=".">','<li><a href="{id_indicateur_amont}" rel="{id_indicateur_amont}">{nom_indicateur_amont}</a></li>','</tpl>','</ul>'),
                                        renderTo: 'indicateurs_amont',
                                        singleSelect: true,
                                        selectedClass: 'none',
                                        itemSelector: 'a',
                                        emptyText: '<div><h5>Aucun indicateur n\'influence cet indicateur...</h35></div>',
                                        store: storeUpstreamIndicators = new Ext.data.Store({
                                            url: strAppUrl + 'services/api.ashx',
                                            reader: new Ext.data.XmlReader({
                                                record: 'indicateur',
                                                id: 'id_indicateur_amont'
                                                }, ['id_indicateur_amont', 'nom_indicateur_amont']
                                            ),
                                            baseParams: {method: 'indicator.getRelated', direction: 'upstream'}
                                        })     
                                            
                                                                                             
                                    })
                                    
                                    
                                ]
                            },
                            {xtype: 'panel', border: true, columnWidth: 0.5, autoHeight: true, id: 'panel_aval', applyTo: 'panel_aval', items: [
                            
                                    viewDownstreamIndicators = new Ext.DataView({
                                        tpl: new Ext.XTemplate('<div><h5>L\'indicateur peut influencer :</h5><ul>','<tpl for=".">','<li><a href="{id_indicateur_aval}" rel="{id_indicateur_aval}">{nom_indicateur_aval}</a></li>','</tpl>','</ul>'),
                                        renderTo: 'indicateurs_aval',
                                        singleSelect: true,
                                        selectedClass: 'none',
                                        itemSelector: 'a',
                                        emptyText: '<div><h5>Cet indicateur n\'influence aucun autre indicateur...</h5></div>',
                                        store: storeDownstreamIndicators = new Ext.data.Store({
                                            url: strAppUrl + 'services/api.ashx',
                                            reader: new Ext.data.XmlReader({
                                                record: 'indicateur',
                                                id: 'id_indicateur_aval'
                                                }, ['id_indicateur_aval', 'nom_indicateur_aval']
                                            ),
                                            baseParams: {method: 'indicator.getRelated', direction: 'downstream'}
                                        })     
                                            
                                                                                             
                                    })
                            
                            
                                ]
                            }
                        ]
                    },
                    {xtype: 'panel', frame: true, border: true, footer: true, autoHeight: true, cls: 'panel', title: 'Variable(s) illustrant l\'indicateur', collapsible: false, id: 'dataPanel', applyTo: 'dataPanel', items: [
                            {xtype: 'panel', layout: 'anchor', frame: false, border: false, autoHeight: true, id: 'dataSourcePanel', applyTo: 'dataSourcePanel', items: [
                                    {xtype: 'uxgroupcombo',
                                        id: 'variablesCombo',
                                        typeAhead: false,
                                        disabled: true,
                                        showGroupName: false,
                                        groupTextTpl: 'Variables compilées sur la base de(s) : {text}',
                                        displayField: 'nom_variable',
                                        valueField: 'id_variable',
                                        hideTrigger: false,
                                        editable: false,
                                        store: storeVariables,
                                        mode: 'local',
                                        triggerAction: 'all',
                                        queryParam: 'indicator_id',
                                        queryDelay: 200,
                                        emptyText: 'Veuillez choisir la variable désirée...'
                                    },
                                    {xtype: 'panel', frame: true, border: true, collapsible: false, autoHeight: true, id: 'metadataPanel', applyTo: 'sourceFieldset'}
                                ]
                            },
                            {xtype: 'panel', layout: 'fit', frame: false, border: true, autoHeight: true, id: 'mapPanel', applyTo: 'mapPanel', items: [
                                    {xtype: 'tabpanel', applyTo: 'mapTabPanel', autoHeight: true, activeTab: 0, frame: false, border: false, deferredRender: false, items: [
                                        {xtype: 'panel', layout: 'column', frame: false, border: false, autoHeight: true, iconCls: 'maptab', headerAsText: false, header: false, title: 'Représentation cartographique', id: 'mapTab', bodyStyle: 'padding: 5px;', applyTo: 'mapTab', items: [
                                                {xtype: 'panel', frame: true, border: true, width: 550, autoHeight: true, id: 'mapWidgetPanel', applyTo: 'mapWidgetPanel',
                                                    bbar: new Ext.StatusBar({
                                                        id: 'mapWidgetStatusbar',
                                                        defaultText: '',
                                                        items: 
                                                        [
                                                            {tooltip: 'Zoom avant', cls:"x-btn-icon", icon: strAppUrl + 'img/icons/zoom_in.png', handler: function() {mapWidget.zoomIn();}},
                                                            {tooltip: 'Zoom arrière', cls:"x-btn-icon", icon: strAppUrl + 'img/icons/zoom_out.png', handler: function() {mapWidget.zoomOut();}},
                                                            '-',
                                                            {tooltip: 'Zoom sur toute la carte', cls:"x-btn-icon", icon: strAppUrl + 'img/icons/zoom_full.png', handler: function() {mapWidget.zoomTo(10);}},
                                                            '-',
                                                            {tooltip: 'Zoom précédent', cls:"x-btn-icon", icon: strAppUrl + 'img/icons/bullet_prev.png', handler: function() {mapHistory.previousTrigger();}},
                                                            {tooltip: 'Zoom suivant', cls:"x-btn-icon", icon: strAppUrl + 'img/icons/bullet_next.png', handler: function() {mapHistory.nextTrigger();}}                                                        ]
                                                    })
                                                },
                                                {xtype: 'panel', layout: 'anchor', frame: false, border: false, columnWidth: 1, autoScroll: true, autoHeight: true, id: 'legendPanel', applyTo: 'legendPanel', items: [
                                                        {xtype: 'combo',
                                                            id: 'locationsCombo',
                                                            emptyText: 'Rechercher un lieu...',
                                                            displayField: 'name',
                                                            typeAhead: false,
                                                            loadingText: 'Un instant...',
                                                            minChars: 2,
                                                            validateOnBlur: false,
                                                            hideTrigger: false,
                                                            store: storeLocations,
                                                            mode: 'remote',
                                                            listWidth: '275',
                                                            listAlign: 'tr-br',
                                                            resizable: false,
                                                            tpl: new Ext.XTemplate('<tpl for=".">','<div class="x-combo-list-item">{nom_lieu}<br/><span style="color: gray">{type}</span></div>','</tpl>'),
                                                            queryParam: 'like',
                                                            queryDelay: 250,
                                                            forceSelection: true,
                                                            selectOnFocus: true
                                                        },
                                                        {xtype: 'fieldset', hideLabels: true, title: 'Limites administratives', autoHeight: true, items: [
                                                                {xtype: 'checkbox', boxLabel: 'Afficher', checked: false, id: 'chkShowMapLimits'}
                                                            ]
                                                        },
                                                        {xtype: 'fieldset', layout: 'anchor', hideLabels: true, title: 'Thématique', id: 'themeFieldSet', autoScroll: true, autoHeight: true, items: [
                                                                {xtype: 'checkbox', boxLabel: 'Afficher', checked: true, id: 'chkShowMapTheme'}
//                                                                {xtype: 'slider', id: 'sliderMapThemeTransparency', autoWidth: true, value: 100, maxValue: 100, minValue: 20, plugins: new Ext.ux.SliderTip()}
                                                           
                                                            ]
                                                        },

                                                        {xtype: 'fieldset', hideLabels: true, title: 'Fond de carte', autoHeight: true, items: [
                                                                {xtype: 'checkbox', boxLabel: 'Afficher', checked: true, id: 'chkShowMapBase'}
                                                            ]
                                                        }
                                                    ]
                                                }
                                            ]
                                        }     
                                    ]}
                                ]
                            },
                            {xtype: 'panel', layout: 'fit', frame: false, border: true, height: 450, id: 'tablePanel', applyTo: 'tablePanel', items: [
                                    {xtype: 'tabpanel', applyTo: 'tableTabPanel', activeTab: 0, frame: false, border: false, deferredRender: false, items: [
                                            {xtype: 'panel', layout: 'fit', id: 'gridPanel', applyTo: 'gridPanel', autoHeight: true, iconCls: 'tabletab', headerAsText: false, header: false, title: 'Représentation tabulaire', bodyStyle: 'padding: 5px;'}
//                                            {xtype: 'panel', layout: 'fit', applyTo: 'chartPanel', autoHeight: true, iconCls: 'charttab', headerAsText: false, header: false, title: 'Représentation graphique', bodyStyle: 'padding: 5px;', disabled: true}
                                        ]
                                    }
                                ]
                            }
                        ] 
                    }
                ]
            });
              
            Ext.getCmp('selectionTabPanel').on('beforetabchange', function(panel, tab) {
            
                Ext.each(tab.findByType('dataview'), function(view, n, items) {
                    if (view.store.getCount() === 0) {
                        view.store.load({callback: function(r, options, success) {tab.doLayout();}});
                    }
                });

            }, this);
                      
            Ext.DomHelper.insertHtml('beforeEnd', Ext.getCmp('themeFieldSet').getEl().dom, Ext.DomHelper.markup({tag: 'div', id: 'themeLegend'}));
            Ext.DomHelper.insertHtml('beforeEnd', Ext.fly('section_title').dom, Ext.DomHelper.markup({tag: 'a', href: "#", style: 'margin-left: 10px;', html: '(changer...)', id: 'btnSelection'}));
                  
            viewAllIndicators.store.load();     
                  
            // Handlers
            
            viewAllIndicators.on('click', function(view, index, node, e) {
            
                if (e.target.className.indexOf('indicateur') >= 0) {
                
                    mainApplicationWindow.dismissBlind(0);
                    Ext.History.add('indicator=' + e.target.rel);
                    
                } else {
                
                    mainApplicationWindow.dismissBlind(0);
                    Ext.History.add('indicator=' + e.target.rel);
                }
                
            }, this, {preventDefault: true});
            
            viewAllObjectives.on('click', function(vw, index, node, e) {
                viewIndicatorsForObjective.store.load({params: {objective_id: e.target.rel}});     
            }, this);
                
            viewIndicatorsForObjective.on('click', function(view, index, node, e) {
                Ext.History.add('indicator=' + e.target.rel);
                mainApplicationWindow.dismissBlind(0);
            }, this, {preventDefault: true});
            
//            Ext.getCmp('description_parcours').doLayout();
            mgr = Ext.getCmp('description_parcours').getUpdater();
            
            var renderer = {};
        
            renderer.render = function(el, response) {
                var responseText = eval('(' + response.responseText + ')');
                el.update(responseText.response.parcourss.parcours.html);
            };
           
            mgr = Ext.getCmp('description_parcours').getUpdater();
            
            mgr.setRenderer(renderer);
        
            mgr.on('update', function(el) {
                el.select('a').on('click', function(e) {
                    //alert(e.target.rel);
                    Ext.History.add('indicator=' + e.target.rel);
                    mainApplicationWindow.dismissBlind(0);
                }, this, {preventDefault: true});   
            }, this);
                        
            viewAllParcours.on('click', function(vw, index, node, e) {           
                 Ext.getCmp('description_parcours').load(strAppUrl + 'services/api.ashx', {format: 'json', method: 'parcours.getDescription', parcours_id: e.target.rel});
            }, this);
            
            viewUpstreamIndicators.on('click', function(vw, index, node, e) {
                Ext.History.add('indicator=' + e.target.rel);
            }, this);
            
            viewUpstreamIndicators.store.on('beforeload', function(store, options) {
                Ext.getCmp('panel_amont').body.mask(Ext.UpdateManager.defaults.indicatorText);
            }, this);
        
            viewUpstreamIndicators.store.on('load', function(store, records, options) {
                Ext.getCmp('panel_amont').body.highlight().unmask();
            }, this);
            
            viewDownstreamIndicators.on('click', function(vw, index, node, e) {
                Ext.History.add('indicator=' + e.target.rel);
            }, this);
        
            viewDownstreamIndicators.store.on('beforeload', function(store, options) {
                Ext.getCmp('panel_aval').body.mask(Ext.UpdateManager.defaults.indicatorText);
            }, this);
                
            viewDownstreamIndicators.store.on('load', function(store, records,  options) {
                Ext.getCmp('panel_aval').body.highlight().unmask();
            }, this);
                        
//            Ext.each(Ext.query('*[class=qtip]'), function(obj, index, scope) {
//            
//                var tip = new Ext.ToolTip({
//                    target: obj,
//                    width: 200,
//                    maxWidth: 200,
//                    height: 200,
//                    bodyStyle: 'padding: 10px;',
//                    shadow: true,
//                    autoLoad: {url: '/help/' + obj.getAttribute('id') + '.txt'},
//                    dismissDelay: 15000, // auto hide after 15 seconds
//                    showDelay: 1000
//                });

//            }, this);
            
            Ext.fly('btnSelection').on('click', function() {mainApplicationWindow.showBlind(0);}, this, {preventDefault: true});
            
//            Ext.getCmp('sliderMapThemeTransparency').on('change', function(obj, value) {
//                mapWidget.getLayer('thematique').setOpacity(value/100);
//            }, this);
            
            Ext.getCmp('chkShowMapLimits').on('check', function(obj, bChecked) {
                toggleMapLayer('limites', bChecked);
            }, this);
            
            Ext.getCmp('chkShowMapTheme').on('check', function(obj, bChecked) {
                toggleMapLayer('thematique', bChecked);
            }, this);
            
            Ext.getCmp('chkShowMapBase').on('check', function(obj, bChecked) {
                toggleMapLayer('google_phys', bChecked);
            }, this);
            
            Ext.getCmp('locationsCombo').on('select', function(combo, record, index) {
                mapWidget.zoomToExtent(OpenLayers.Bounds.fromString(record.get('bounds')));
            }, this);
            
            Ext.getCmp('variablesCombo').on('select', function(combo, record, index) {
                switchVariable(record.get('id_variable'));
            }, this);
            
            Ext.History.on('change', handleHistoryChange, this); 
              
            var href = top.location.href, i = href.indexOf("#");
            initialIndicator = i >= 0 ? href.substr(i + 1) : null;
            
            mainApplicationWindow.doLayout();
            
            var fadeCallback = function() {
            
                Ext.fly('loadingWindow').fadeOut({duration: 0.5, callback: function() {
                
                        if (initialIndicator === null) {
                            mainApplicationWindow.showBlind(0);
                        } else {
                            handleHistoryChange(initialIndicator);
                        }
                
                    }
                }).remove();
            
            };
            
            if (Ext.isIE) {
                var callback = fadeCallback.createSequence(function() {Ext.fly('conteneur_donnees').show();});
                callback();
            } else {
                Ext.fly('conteneur_donnees').fadeIn({duration: 0.5, callback: fadeCallback}, this);
            }
            
            logMessage('Socioscope explorer module started...');
                        
        }
    
    };

}();

// Redefine default printing function...
socioscope.print = socioscope.explorerModule.printHandler;

// Start module...
Ext.onReady(socioscope.explorerModule.init, socioscope.explorerModule);






