/**
 * SIGDT2D specific stuff
 */
var sigdt = {
    map: null,
    mapMinWidth: '50%',
    mapMinHeight: 620,
    mapMaxWidth: 700,
    mapInitWidth: '50%',
    mapInitHeight: 250,
    mapMaxHeight: 1005,
    metadataPopupWidth: 600,
    metadataPopupHeight: 500,
    
    overviewWmsUrl: '/'+window.baseGeoserver+'wms?',
    overviewWmsLayers: 'fond_carto_mali',
    overviewWmsFormat: 'image/jpeg',
    
    pratiquesGDT_vectorLayer:null,
    pratiquesGDT_vectorMark_style:OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']),
    

    initialize: function(tdata) {
        //var model = Ext.util.JSON.decode(tdata);
        var model=null;
        model = window.layersModel;
        //console.log(model);
        Ext.QuickTips.init();
        Ext.apply(Ext.QuickTips.getQuickTip(), {
            //autoWidth: true,
            maxWidth : 300,
            trackMouse: true
        });

        Ext.getBody().createChild({id:'map'});
//        var map = sigdt.map = createMap('map', false);      
        var mapCmp = new SigdtMapComponent('map', {enableNavigation:true, model:model});
        var map = sigdt.map = mapCmp.map;
        //console.log(mapCmp);

        var toolbar = mapCmp.getToolbar();
        
        var mk_raccourcis = '<h1>Ecosystèmes</h1>'
                      +'<input type="text" id="cb_ecosys" size="20"/>'
                      +'<h1>Entités administratives</h1>'
                      +'<input type="text" id="cb_regions" size="20"/>'
                      +'<input type="text" id="cb_cercles" size="20"/>'
                      +'<input type="text" id="cb_communes" size="20"/>';
        var mk_pratiques = '<h1>Carte des pratiques GDT</h1>'
                      +'<input type="text" id="cb_GDTfamilles" size="20"/>'
                      +'<input type="text" id="cb_GDTpratiques" size="20"/>';
                    
        this.viewPort = new Ext.Viewport({
            layout: 'border',
            items: [{
                region: 'north',
                contentEl: 'north',
                //title : translate('sigdt-title'),
                autoHeight: true,
                collapsible:true,
                border: true
            },{
                region: 'center',
                split: true,
                id: 'mapRegion',
                layout: 'fit',
                tbar: toolbar,
                border: true,
                contentEl: 'map'
            },{
                region: 'west',
                id: 'westMap',
                title:translate('westPanel'),
                width: '250',
                border: true,
                split: true,
                collapsible: true,
                collapsed: false,
                autoScroll:true,
                layout: 'anchor',
                defaults: {
                  border: false,
                  collapsible: true,
                        frame:false
                },
                layoutConfig:{
                    animate: true
                },
                items: [{ 
                        title:translate('shortcuts'),
                        id:'raccourcisPanel',
                        html:mk_raccourcis,
                        autoHeight: true,
                        cls:"lang-panel"
                },{ 
                        title:translate('pratiques'),
                        id:'pratiquesPanel',
                        html:mk_pratiques,
                        autoHeight: true,
                        cls:"lang-panel"
                },{ 
                        title: translate('layerTree'),
                        xtype: 'layertree',
                        id: 'LayerTree',
                        map: this.map,
                        model: model,
                        enableDD: true,
                        ascending: true,
                        autoHeight: true,
                        collapsible: true,
                        collapsed: false,
                        plugins: [
                            mapfish.widgets.LayerTree.createContextualMenuPlugin(['opacitySlide','remove'])
                        ]
                }]  
            }/*,{
                region: 'east',
                title: 'Layers',
                xtype: 'layertree',
                id: 'LayerTree',
                map: this.map,
                enableDD: true,
                ascending: true,
                width: 250,
                split: true,
                collapsible: true,
                collapsed: false,
                plugins: [
                    mapfish.widgets.LayerTree.createContextualMenuPlugin(['opacitySlide','remove'])
                ]
            }*/],
            listeners: {
                render: function() {
                    //get rid of the loading mask
                    Ext.get('loading').remove();
                    Ext.fly('loading-mask').fadeOut({
                        remove:true
                    });

                    //Ext.get("searchResults").show(); //search results where with "display:none" to avoid having the loading screen with a scrollbar
                }
            }
        });
        this.buildRaccourcis();
        this.buildPratiquesCombos();
        mapCmp.fillToolbar();
        mapCmp.zoomToFullExtent();
        this.addTooltips();
    },
       
    addTooltips: function() {
      //map toolbar buttons
      new Ext.ToolTip({
        target: Ext.DomQuery.select("button[@class*='x-btn-text zoomfull']")[0],
        title: translate('zoomfull'),
        width:300,
        html: translate('zoomfull-ttip')
      });
      new Ext.ToolTip({
        target: Ext.DomQuery.select("button[@class*='x-btn-text zoomin']")[0],
        title: translate('zoomin'),
        width:300,
        html: translate('zoomin-ttip')
      });
      new Ext.ToolTip({
        target: Ext.DomQuery.select("button[@class*='x-btn-text zoomout']")[0],
        title: translate('zoomout'),
        width:300,
        html: translate('zoomout-ttip')
      });
      new Ext.ToolTip({
        target: Ext.DomQuery.select("button[@class*='x-btn-text pan']")[0],
        title: translate('pan'),
        width:300,
        html: translate('pan-ttip')
      });
      new Ext.ToolTip({
        target: Ext.DomQuery.select("button[@class*='x-btn-text info']")[0],
        title: translate('query-button'),
        width:300,
        html: translate('query-button-ttip')
      });

    },
    createMap:function(mapDiv, model) {
      var options = {
        projection: "EPSG:4326",
        units: 'degrees',
        numZoomLevels: 20,
        maxExtent: OpenLayers.Bounds.fromString("-23,21,35,41"),
          //tileSize: new OpenLayers.Size(512, 512),
        maxResolution: 0.0703125,
        controls: [
            new OpenLayers.Control.MouseDefaults(),
            //new OpenLayers.Control.MouseToolbar(),
            new OpenLayers.Control.PanZoomBar(),
    //                    new OpenLayers.Control.LayerSwitcher({'ascending':false}),
    //                    new OpenLayers.Control.Permalink(),
            new OpenLayers.Control.ScaleLine(),
            //new OpenLayers.Control.Scale(),
    //                    new OpenLayers.Control.Permalink('permalink'),
            new OpenLayers.Control.KeyboardDefaults()
          ]
      };   

      var map = new OpenLayers.Map(mapDiv, options);

      var bounds = new OpenLayers.Bounds();
      for (var j=0 ; j < model.length ; j++)
      {
        for(i=0 ; i < model[j].children.length;i++)  
        {
          var child = model[j].children[i];
          this.addLayerToMap(map, child);
        }
      }
      //map.addControl(new OpenLayers.Control.LayerSwitcher());
      map.setCenter(new OpenLayers.LonLat(5,45), 2);
      //map.addControl(new OpenLayers.Control.PanZoom({div: $('navToolBar')}));
      OpenLayers.IMAGE_RELOAD_ATTEMPTS = 3;

      return map;
    },
    addLayerToMap:function(map, child)
    {
      var wms;
      if (child.bbox!=null)
        bounds = OpenLayers.Bounds.fromString(child.bbox);
      else 
        bounds = OpenLayers.Bounds.fromString("-180,-90,180,90");
        
      var layername = child.layerName;
      if (child.datatype=="WorldWind")
      {
        //console.info("adding worldwind layer : "+child.layerName + ", "+child.datatype);
        wms = new OpenLayers.Layer.WorldWind(layername,
          child.url,child.lztd, child.numlevels-1,
          {T: child.layers, FORMAT: child.format, LAYERS:child.layers},
          {isBaseLayer: child.isbaselayer, transitionEffect: 'resize',maxExtent:bounds}
        );
      }
      else
      {
        //console.info("adding wms layer : "+child.layerName + ", "+child.datatype);
        wms = new OpenLayers.Layer.WMS(layername,
          child.url, 
          {layers: child.layers, TRANSPARENT:"TRUE", BGCOLOR: '0xFF00FF', styles: child.styles },
          {isBaseLayer: child.isbaselayer, transitionEffect: 'resize',maxExtent:bounds}
        );
      }
      
       wms.buffer=0;
      wms.setVisibility(child.checked);
      if (child.opacity!=null)
        wms.setOpacity(child.opacity);
      if (child.lztd!=null)
        wms.addOptions({lztd: child.lztd});
      map.addLayer(wms);
      if(child.queryable==true)
        wms.addOptions({queryable: true});
      wms.unique_id = child.oid;
    } ,
    buildRaccourcis: function() {
      //
      //Raccourcis sur les zonages "Ecosystèmes"
      //
      var store_zonages = new Ext.data.Store({
        // load using HTTP
        url: window.baseURL+'sigdt-fiches/emprise.php?table=zonages',

        // the return will be XML, so lets set up a reader
        reader: new Ext.data.XmlReader({
               // records will have an "emprise" tag
               record: 'emprise',
               id: '@id'
           }, [
               // set up the fields mapping into the xml doc
               {name: 'id', mapping:'@id'},
               {name: 'nom'},
               {name: 'yUL'},
               {name: 'yLR'},
               {name: 'xLR'},
               {name: 'xUL'}
           ]),
        sortInfo : {field: "id", direction: "ASC"}
        });
      var combo_zonages = new Ext.form.ComboBox({
          store: store_zonages,
          displayField:'nom',
          forceSelection: true,
          triggerAction: 'all',
          emptyText:'Choisir...',
          selectOnFocus:true,
          applyTo: 'cb_ecosys'
      });
      combo_zonages.on('select', function(combo, record, index) {
        /*if (console!=null)
        {
          console.log(record);
        }*/
        var bbox = new OpenLayers.Bounds(
                                      parseFloat(record.get('xUL')),
                                      parseFloat(record.get('yLR')),
                                      parseFloat(record.get('xLR')),
                                      parseFloat(record.get('yUL'))
                                  );
        if (sigdt.map!=null)
          sigdt.map.zoomToExtent(bbox);
      });
      
      //
      //Raccourcis sur les zonages administratifs : region / cercle / commune
      //
      var store_regions = new Ext.data.Store({
        // load using HTTP
        url: window.baseURL+'sigdt-fiches/emprise.php?table=regions',

        // the return will be XML, so lets set up a reader
        reader: new Ext.data.XmlReader({
               // records will have an "emprise" tag
               record: 'emprise',
               id: '@id'
           }, [
               // set up the fields mapping into the xml doc
               {name: 'id', mapping:'@id'},
               {name: 'nom'},
               {name: 'yUL'},
               {name: 'yLR'},
               {name: 'xLR'},
               {name: 'xUL'}
           ]),
        sortInfo : {field: "id", direction: "ASC"}
        });
      var combo_regions = new Ext.form.ComboBox({
          store: store_regions,
          displayField:'nom',
          forceSelection: true,
          triggerAction: 'all',
          emptyText:'Régions...',
          selectOnFocus:true,
          applyTo: 'cb_regions'
      });
      combo_regions.on('select', function(combo, record, index) {
        /*if (console!=null)
        {
          console.log(record);
        }*/
        var bbox = new OpenLayers.Bounds(
                                      parseFloat(record.get('xUL')),
                                      parseFloat(record.get('yLR')),
                                      parseFloat(record.get('xLR')),
                                      parseFloat(record.get('yUL'))
                                  );
        if (sigdt.map!=null)
          sigdt.map.zoomToExtent(bbox);
        
        combo_cercles.clearValue();
        combo_cercles.store.filter('region', record.id); //marche si le combo a déjà été chargé une fois (sinon, cf store_cercles.on('load'... )
        combo_communes.clearValue();
        combo_communes.store.filter('region', record.id); //marche si le combo a déjà été chargé une fois (sinon, cf store_communes.on('load'... )
        this.selectedRecord = record; 
      });
      var store_cercles = new Ext.data.Store({
        // load using HTTP
        url: window.baseURL+'sigdt-fiches/emprise.php?table=cercles',

        // the return will be XML, so lets set up a reader
        reader: new Ext.data.XmlReader({
               // records will have an "emprise" tag
               record: 'emprise',
               id: '@id'
           }, [
               // set up the fields mapping into the xml doc
               {name: 'id', mapping:'@id'},
               {name: 'nom'},
               {name: 'region'},
               {name: 'yUL'},
               {name: 'yLR'},
               {name: 'xLR'},
               {name: 'xUL'}
           ]),
        sortInfo : {field: "id", direction: "ASC"}
        });
      store_cercles.on('load', function(store) { //sert au moment du premier chargement. Le reste du temps, c'est réalisé directement par une directive filter dans l'évènement select
        //console.log(combo_regions.selectedRecord);
        //console.log(this);
        if (combo_regions.selectedRecord!=null)
          this.filter('region', combo_regions.selectedRecord.id);
      });
      var combo_cercles = new Ext.form.ComboBox({
          store: store_cercles,
          displayField:'nom',
          forceSelection: true,
          lazyInit:false,
          triggerAction: 'all',
          emptyText:'Cercles...',
          selectOnFocus:true,
          applyTo: 'cb_cercles'
      });
      combo_cercles.on('select', function(combo, record, index) {
        /*if (console!=null)
        {
          console.log(record);
        }*/
        var bbox = new OpenLayers.Bounds(
                                      parseFloat(record.get('xUL')),
                                      parseFloat(record.get('yLR')),
                                      parseFloat(record.get('xLR')),
                                      parseFloat(record.get('yUL'))
                                  );
        if (sigdt.map!=null)
          sigdt.map.zoomToExtent(bbox);
        
        combo_communes.clearValue();
        combo_communes.store.filter('cercle', record.id);//marche si le combo a déjà été chargé une fois (sinon, cf store_communes.on('load'... )
        this.selectedRecord = record;
      });
      
      var store_communes = new Ext.data.Store({
        // load using HTTP
        url: window.baseURL+'sigdt-fiches/emprise.php?table=communes',

        // the return will be XML, so lets set up a reader
        reader: new Ext.data.XmlReader({
               // records will have an "emprise" tag
               record: 'emprise',
               id: '@id'
           }, [
               // set up the fields mapping into the xml doc
               {name: 'id', mapping:'@id'},
               {name: 'nom'},
               {name: 'cercle'},
               {name: 'region'},
               {name: 'yUL'},
               {name: 'yLR'},
               {name: 'xLR'},
               {name: 'xUL'}
           ]),
        sortInfo : {field: "id", direction: "ASC"}
        });
      store_communes.on('load', function(store) { //sert au moment du premier chargement. Le reste du temps, c'est réalisé directement par une directive filter dans l'évènement select
        if (combo_cercles.selectedRecord!=null)
          this.filter('cercle', combo_cercles.selectedRecord.id);
        else if (combo_regions.selectedRecord!=null)
          this.filter('region', combo_regions.selectedRecord.id);
      });
      var combo_communes = new Ext.form.ComboBox({
          store: store_communes,
          displayField:'nom',
          forceSelection: true,
          triggerAction: 'all',
          emptyText:'Communes...',
          selectOnFocus:true,
          applyTo: 'cb_communes'
      });
      combo_communes.on('select', function(combo, record, index) {
        /*if (console!=null)
        {
          console.log(record);
        }*/
        var bbox = new OpenLayers.Bounds(
                                      parseFloat(record.get('xUL')),
                                      parseFloat(record.get('yLR')),
                                      parseFloat(record.get('xLR')),
                                      parseFloat(record.get('yUL'))
                                  );
        if (sigdt.map!=null)
          sigdt.map.zoomToExtent(bbox);
      });
    },
    buildPratiquesCombos: function() {
      //
      //Combo sur les grandes catégories de pratiques GDT
      //
      var store_GDTfamilles = new Ext.data.Store({
        // load using HTTP
        url: window.baseURL+'sigdt-fiches/ecosys_pratiques.php?table=tfamillepratiques',

        // the return will be XML, so lets set up a reader
        reader: new Ext.data.XmlReader({
               // records will have an "emprise" tag
               record: 'item',
               id: '@id'
           }, [
               // set up the fields mapping into the xml doc
               {name: 'id', mapping:'@id'},
               {name: 'nom'}
           ]),
        sortInfo : {field: "id", direction: "ASC"}
        });
      var combo_GDTfamilles = new Ext.form.ComboBox({
          store: store_GDTfamilles,
          displayField:'nom',
          forceSelection: true,
          triggerAction: 'all',
          emptyText:'Famille de pratiques...',
          selectOnFocus:true,
          applyTo: 'cb_GDTfamilles'
      });
      combo_GDTfamilles.on('select', function(combo, record, index) {
        this.selectedRecord = record;
        combo_GDTpratiques.enable();
        combo_GDTpratiques.emptyText= "Pratiques ["+record.get("nom")+"]";
        combo_GDTpratiques.clearValue();
        combo_GDTpratiques.store.filter('categorie', record.id);//marche si le combo a déjà été chargé une fois (sinon, cf store_communes.on('load'... )

      });
      //
      //Combo sur les pratiques GDT
      //
      var store_GDTpratiques = new Ext.data.Store({
        // load using HTTP
        url: window.baseURL+'sigdt-fiches/ecosys_pratiques.php?table=tpratiques',

        // the return will be XML, so lets set up a reader
        reader: new Ext.data.XmlReader({
               // records will have an "emprise" tag
               record: 'item',
               id: '@id'
           }, [
               // set up the fields mapping into the xml doc
               {name: 'id', mapping:'@id'},
               {name: 'categorie', mapping:'@ordre'},
               {name: 'nom'}
           ]),
        sortInfo : {field: "categorie", direction: "ASC"}
        });
      store_GDTpratiques.on('load', function(store) { //sert au moment du premier chargement. Le reste du temps, c'est réalisé directement par une directive filter dans l'évènement select
        if (combo_GDTfamilles.selectedRecord!=null)
          this.filter('categorie', combo_GDTfamilles.selectedRecord.id);
      });
      var combo_GDTpratiques = new Ext.form.ComboBox({
          store: store_GDTpratiques,
          displayField:'nom',
          forceSelection: true,
          autoWidth:true,
          listWidth:300,
          disabled:true,
          triggerAction: 'all',
          emptyText:'Choisir...',
          resizable:true,
          selectOnFocus:true,
          applyTo: 'cb_GDTpratiques'
      });
      sigdt.pratiquesGDT_vectorMark_style.pointRadius = 4;
      combo_GDTpratiques.on('select', function(combo, record, index) {
        this.selectedRecord = record;
        if (record.get('id')==null) 
          return false;
        var store_zonagesPratique = new Ext.data.Store({
          // load using HTTP
          url: window.baseURL+'sigdt-fiches/emprise.php?table=zonages&codePratique='+record.get('id'),

          // the return will be XML, so lets set up a reader
          reader: new Ext.data.XmlReader({
                 // records will have an "emprise" tag
                 record: 'emprise',
                 id: '@id'
             }, [
                 // set up the fields mapping into the xml doc
                 {name: 'id', mapping:'@id'},
                 {name: 'nom'},
                 //{name: 'yUL'},
                 //{name: 'yLR'},
                 //{name: 'xLR'},
                 {name: 'lat'},
                 {name: 'lon'},
                 {name: 'importance'}
             ]),
          sortInfo : {field: "importance", direction: "ASC"}
        });
        store_zonagesPratique.load();
        //alert(record.get('nom'));
        store_zonagesPratique.on('load', function() { 
          if (sigdt.pratiquesGDT_vectorLayer==null)
          {
            sigdt.pratiquesGDT_vectorLayer = new OpenLayers.Layer.Vector();
            sigdt.map.addLayer(sigdt.pratiquesGDT_vectorLayer);
          }
          else
            sigdt.pratiquesGDT_vectorLayer.destroyFeatures();
          this.each(function (record) {
            var point = new OpenLayers.Geometry.Point(record.get("lon"), record.get("lat"));
            var pointFeature = new OpenLayers.Feature.Vector(point,null,sigdt.pratiquesGDT_vectorMark_style);
            sigdt.pratiquesGDT_vectorLayer.addFeatures([pointFeature]);
          });
        });
      });
    }
};

