/*
 * Copyright © 2008  Neogeo Technologies, Toulouse, France

 * This file is part of Opencarto web map publishing system project
 *
 * Opencarto is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Opencarto is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with Opencarto.  If not, see <http://www.gnu.org/licenses/>.
 */
Ext.BLANK_IMAGE_URL = '/locazone_media/js/ext-2.2/resources/images/default/s.gif';
Ext.namespace('opencarto');
opencarto.tm = null; // timeout
opencarto.gisobjects = {};
opencarto.layercounter = 0;
opencarto.lastControlUsed = 'olControlNavigation';

Ext.onReady(function() {
    // chargement du flux JSON d'initialisation
    Ext.Ajax.request({
		url:'layers/',
		success:function(res,opt) {   
            eval('opencarto.gisobjects = ' + res.responseText);
            // ajout des deux fonds rasters
            	opencarto.gisobjects.layers.unshift({"name":"plannb","label":"Plan de ville N&B","alwaysInRange":false,"url":['http://data1.opencarto.fr/tc43/?','http://data2.opencarto.fr/tc43/?','http://cugt.opencarto.fr/tc43/?'],
                "params":{"layers":"planvilleNB","format":"image/png"},
                "options":{"format":"image/png","layerid":0,"alpha":true,"opacity":100,"showInLegend":false,"resolutions":globalParams.resolutions,"buffer":0,"exporter":false,"visibility":false,"groupe":0,"attribution":'Plan de Ville 2009 &copy Grand Toulouse',
                    "groupname":"Fond","grouporder":"0","rang":4,"typegeo":"RASTER","sld":"null","search":false}});
            	opencarto.gisobjects.layers.unshift({"name":"mixte","label":"Fond cartographique","alwaysInRange":false,"url":['http://data1.opencarto.fr/tc43/?','http://data2.opencarto.fr/tc43/?','http://cugt.opencarto.fr/tc43/?'],
                "params":{"layers":"mixte","format":"image/png"},
                "options":{"format":"image/png","layerid":0,"alpha":true,"opacity":100,"showInLegend":false,"resolutions":globalParams.resolutions,"buffer":0,"exporter":false,"visibility":false,"groupe":0,"attribution":'Plan de Ville 2009 et Image aérienne 2009 &copy Grand Toulouse',
                    "groupname":"Fond","grouporder":"0","rang":3,"typegeo":"RASTER","sld":"null","search":false}});
            	opencarto.gisobjects.layers.unshift({"name":"ortho","label":"Fond cartographique","alwaysInRange":false,"url":['http://data1.opencarto.fr/tc43/?','http://data2.opencarto.fr/tc43/?','http://cugt.opencarto.fr/tc43/?'],
                "params":{"layers":"ortho","format":"image/jpeg"},
                "options":{"format":"image/jpeg","layerid":0,"alpha":true,"opacity":100,"showInLegend":false,"resolutions":globalParams.resolutions,"buffer":0,"exporter":false,"visibility":false,"groupe":0,"attribution":'Image aérienne 2009 &copy Grand Toulouse',
                    "groupname":"Fond","grouporder":"0","rang":2,"typegeo":"RASTER","sld":"null","search":false}});
            
            	
            	opencarto.gisobjects.layers.unshift({"name":"planville","label":"Plan de ville","alwaysInRange":false,"url":['http://data1.opencarto.fr/tc43/?','http://data2.opencarto.fr/tc43/?','http://cugt.opencarto.fr/tc43/?'],
                "params":{"layers":"planville","format":"image/png"},
                "options":{"format":"image/png","layerid":0,"alpha":true,"opacity":100,"showInLegend":false,"resolutions":globalParams.resolutions,"buffer":0,"exporter":false,"visibility":true,"groupe":0,
"attribution":'Plan de ville 2009, &copy Grand Toulouse',
                    "groupname":"Fond","grouporder":"0","rang":1,"typegeo":"RASTER","sld":"null","search":false}});
            
                
/*            opencarto.gisobjects.layers.push({"name":"POI","label":"Points de contact","alwaysInRange":true,"url":"",
               
                "options":{"layerid":0,"alpha":true,"opacity":100,"showInLegend":true,"resolutions":globalParams.resolutions,"buffer":0,"exporter":false,"visibility":false,"groupe":2,
                    "groupname":"Grand Toulouse","grouporder":"4","rang":6,"typegeo":"Point","sld":"null","search":false}});
*/
            // chargement éventuel du panneau de contrôle des couches
            if (opencarto.layerControl)
            	opencarto.layerControl.load();
            // chargement des couches dans la carte (cf OCmap.js)
 			opencarto.loadLayers();
 			// affichage éventuel de la légende
            if (opencarto.legend)
            	opencarto.legend.show();
		},
		failure: function(res,opt){
		   	Ext.Msg.show({
                title: oMessages.error_title,
                msg: oMessages.error_load_layers,buttons: Ext.Msg.OK,icon: Ext.MessageBox.ERROR
            });
		   	return;
		}   
	});
   // FIN DE LA FONCTION AJAX DE CHARGEMENT DES COUCHES

	// début "vrai" du script, car le contenu de la fonction Ajax est effectué après
	// Préparation des options de  l'objet carte OpenLayers
   opencarto.createMap();
    
    // Création du panel cartographique
    opencarto.mapPanel = new Ext.ol.OLPanel(mapOptions);

    
   
   // création du contenu des panneaux en fonction des modules chargés
    if (opencarto.legend){
    	opencarto.legendPanel = new Ext.Panel({
            id: 'legendPanel',
            title: 'Légende',
            iconCls: 'legend',
            collapsible:true,
            border:true,
            frame:false,
            autoScroll:true,
            autoHeight:true,
            titleCollapse: true,
            bodyStyle: 'background-image:url(/locazone_media/images/logo_gt.png);background-repeat: no-repeat;'
    	});
    
    }
    else{
    	// on crée quand même un panel bidon, pour pouvoir créér le panneau gauche (à moins que...)
    	opencarto.legendPanel = new Ext.Panel({
            id: 'legendPanel',
            title: '',
            collapsible:true,
            collapsed:true,
            border:true,
            frame:false,
            autoScroll:true,
            autoHeight:true,
            titleCollapse: true
    	})
    }
    
    opencarto.toolbar = new Ext.Toolbar();
    opencarto.Mask = new Ext.LoadMask(Ext.getBody(), {msg:"Merci de patienter..."});
    opencarto.bbar = new Ext.StatusBar({
        defaultText: 'Prêt',
        autoHeight:true,
        id: 'basic-statusbar',
        busyText:'Chargement en cours...'
        //items: [{xtype: 'tbtext',text:'Système de coordonnées : ' + globalParams.projectionName}, ' ', ' ']
    });
    
    opencarto.drawbar = new Ext.Toolbar();
    
    
    opencarto.mainPanel = new Ext.Panel({
        region:'center',
        layout: 'border',
        border: false,
        frame:false,
        bbar:opencarto.bbar,
        items:[{
            region: 'center',
            tbar:opencarto.toolbar,
            title: globalParams.mapLibelle,
            layout: 'fit',
            collapsible: true,
            collapsed: false,
            split: true,
            
            minSize: 100,
            maxSize: 500,
            items: [opencarto.mapPanel]
        }]

    })
    // ajout du datagrid si un module le nécessite
    if (opencarto.layerControl && opencarto.displayDataGrid){
    	opencarto.mainPanel.items.add(opencarto.datagrid.panel);
    }
    // création du panneau gauche si nécessaire
    if (opencarto.legend || opencarto.layerControl || opencarto.position || opencarto.vues){
	    opencarto.leftPanel = new Ext.Panel({
            region:'west',
            id:'west-panel',
            //title:'OUTILS',
            split:true,
            width: 250,
            minSize: 175,
            maxSize: 400,
            animate:true,
            collapsible: false,
            collapseMode: 'mini',
            collapsed:false,
            border:false,
            margins:'0 0 0 0',
            autoScroll:true,
            items: [opencarto.legendPanel],
            listeners:{
                collapse:opencarto.resizeMap,
                expand:opencarto.resizeMap
            }
	    	
	    })
	}
gtCities = { cities:[
	{id:'31555', name:'Toulouse'},
	{id:'31205', name:'Gagnac-sur-Garonne'},
	{id:'31541', name:'Seilh'},
	{id:'31116', name:'Castelginest'},
	{id:'31467', name:'Saint-Alban'},
	{id:'31182', name:'Fenouillet'},
	{id:'31032', name:'Aussonne'},
	{id:'31351', name:'Mondonville'},
	{id:'31186', name:'Fonbeauzard'},
	{id:'31022', name:'Aucamville'},
	{id:'31282', name:'Launaguet'},
	{id:'31056', name:'Beauzelle'},
	{id:'31150', name:'Cornebarrieu'},
	{id:'31069', name:'Blagnac'},
	{id:'31417', name:'Pibrac'},
	{id:'31088', name:'Brax'},
	{id:'31149', name:'Colomiers'},
	{id:'31557', name:'Tournefeuille'},
	{id:'31157', name:'Cugnaux'},
	{id:'31588', name:'Villeneuve Tolosane'},
	{id:'31561', name:'L\'Union'},
	{id:'31044', name:'Balma'},
	{id:'31418', name:'Pin Balma'},
	{id:'31445', name:'Quint-Fonsegrives'},
	{id:'31506', name:'Saint-Orens-de-Gameville'}
	]
}
opencarto.gtCities = new Ext.form.ComboBox({
               id: 'cbpoitype',
               fieldLabel: "Commune",
               displayField: 'name',
               hiddenName:'poitype',
               allowBlank:false,
               valueField: 'id',
               width: 170,
               height: 30,
               editable: false,
               typeAhead: true,
               mode: 'local',
               triggerAction: 'all',
               forceSelection:true,
               value:'31555',
               lazyInit:false,
               selectOnFocus: true,
               store: new Ext.data.JsonStore({
                    data: gtCities,
                    root: 'cities',
                    sortInfo: {field: "name", direction: "ASC"},
                    fields: ['id', 'name']
               })
            });

// ajout formulaire de recherche d'adresse
opencarto.searchForm  =new Ext.form.FormPanel({
        labelWidth:60,
        frame:true,
//                title:"Trouver une adresse...",
        items:[
                        {
                        xtype:'textfield',
                        fieldLabel: 'Adresse',
                        name: 'adresse',
                        id:'find_adresse',
                        width: 170,
                        minLength:3
                        },
		opencarto.gtCities
        ]
    });

opencarto.searchPanel = new Ext.Panel({
    id: 'searchPanel',
    title: 'Localisation',
    iconCls: 'positions',
    collapsible:true,
    border:false,
    frame:false,
    titleCollapse: true,
    items :[
            opencarto.searchForm
           ]
    });
opencarto.searchForm.addButton('Afficher', opencarto.getLocation);
opencarto.searchForm.addButton('Effacer', opencarto.resetSearch);
opencarto.leftPanel.insert(0,opencarto.searchPanel);
    
    // ajout éventuel du panneau des positions
    if (opencarto.position){
    	opencarto.leftPanel.insert(0,opencarto.position.positionPanel);
		// et de la fonction d'ajout si l'utilisateur est administrateur
    	if (globalParams.userAdmin === true)
    	opencarto.position.positionForm.addButton({text: oMessages.add_view, tooltipType:'title', tooltip:"Ajout de la position courante", handler: opencarto.addPosition})
    
    }
    
 // ajout éventuel du formulaire vues
    if (opencarto.vues){
    	opencarto.leftPanel.insert(0,opencarto.vues.vuesPanel);
    	// et de la fonction d'ajout si l'utilisateur est administrateur
    	if (globalParams.userAdmin === true)
    	opencarto.vues.vuesForm.addButton({text: 'Ajouter la vue courante', tooltipType:'title', tooltip:"Ajout de la vue courante", handler: opencarto.vues.addVue})
    }
 
    // préparation du contenu de la vue principale
    viewportItems = new Array(opencarto.mainPanel);	
    if (opencarto.leftPanel){
    	viewportItems.unshift(opencarto.leftPanel);
    } 
    // création du viewport (vue principale)
    opencarto.viewport = new Ext.Viewport({
            layout:'border',
            items:viewportItems
    });
    
    // ajout éventuel du bouton 'Administration' en bas à droite
    if (globalParams.userAdmin === true){
        opencarto.bbar.addButton({text: 'Administration', tooltipType:'title', tooltip:"Accès au module d'administration", handler: opencarto.adminHandler});
    }   
    // chargement du contenu par défaut de la Toolbar (toolbar.js)
	opencarto.loadToolbar();
    
 // ajout éventuel de la barre d'outils de dessin
    if ( opencarto.geoEditor ){
    	opencarto.toolbar.add(opencarto.drawbar );
    	opencarto.geoEditor.loadtools();
	}
    
    // mise en attente de la statusbar du bas
    opencarto.bbar.showBusy();
    // à l'initialisation, OpenLayers n'arrive pas à récupérerle x,y du curseur, alors on l'aide :
    // hack pour bon redimensionnement du MapPanel au lancement, et le recalcul du x,y du curseur par OpenLayers.fuck
    if (window.outerWidth)
        window.outerWidth = window.outerWidth - 1;
    else if (document.documentElement.clientWidth)
        window.resizeTo(document.documentElement.clientWidth-1,document.documentElement.clientHeight + 160);
        
        
  
});




