/*
 * Ext JS Library 2.2
 * Copyright(c) 2006-2008, Ext JS, LLC.
 * licensing@extjs.com
 * 
 * http://extjs.com/license
 */

//
// This is the main layout definition.
//
Ext.onReady(function(){
	
	Ext.QuickTips.init();
	
	
	// This is an inner body element within the Details panel created to provide a "slide in" effect
	// on the panel body without affecting the body's box itself.  This element is created on
	// initial use and cached in this var for subsequent access.
	var detailEl;
	
	
	// module captcha pour l'envoi d'email
	var randomnumber1 = Math.floor(Math.random()*11);
	var randomnumber2 = Math.floor(Math.random()*11);
	
	// Go ahead and create the TreePanel now so that we can use it below
    var treePanel = new Ext.tree.TreePanel({
    	id: 'tree-panel',
    	title: 'Points d\'intérêt',
        region: 'north',
        split: true,
        height: 370,
        minSize: 150,
        autoScroll: true,
        
        // tree-specific configs:
        rootVisible: false,
		autoScroll: true,
		useArrows: true,
		loader: new Ext.tree.TreeLoader({
            dataUrl: './json_file/tree-layer-data.json',
			baseAttrs:{
				uiProvider:Ext.tree.TriStateNodeUI
			}
        }),
        root: new Ext.tree.AsyncTreeNode()
    });
	
	// This is the main content center region that will contain each example layout panel.
	// It will be implemented as a CardLayout since it will contain multiple panels with
	// only one being visible at any given time.
	
	var sm = new Ext.grid.CheckboxSelectionModel();
	
	var buttonKmz = new Ext.Button({
		id: 'button_kmz',
		text: 'Télécharger le KML',
		handler: function(){
			var listDownloadChecked = new Array();
			for (i=0;i<Ext.getCmp('grid_download').getSelectionModel().getSelections().length;i++){
				var id_cat = Ext.getCmp('grid_download').getSelectionModel().getSelections()[i].id;
				listDownloadChecked.push(id_cat);
			}
			Ext.Ajax.request({
				url: './php_geopyrenees/getKml.php?listDownloadChecked='+listDownloadChecked,
				success: function (response) {
					var res = Ext.util.JSON.decode(response.responseText);
					if (res.success == true){
	                    Ext.Msg.buttonText.cancel = 'Fermer';
	                    Ext.Msg.show({
	                        title: 'Téléchargement',
							msg: '<a href="./php_geopyrenees/downloadFile.php?file=' + res.file + '"><div style="text-decoration:underline;color:#000000">Cliquer ici pour enregistrer le fichier sur votre ordinateur.</div></a>',
	                        buttons: Ext.Msg.CANCEL,
	                        icon: Ext.Msg.INFO,
							minWidth: 400
	                    });
					}
					else{
						Ext.Msg.show({
							title: 'Attention',
							msg: '<div style="color:#000000">Veuillez sélectionner au moins une catégorie.</div>',
							buttons: Ext.Msg.OK,
							icon: Ext.Msg.WARNING,
							minWidth: 350
						});
					}
                }
			});
		}
	});
	
	var buttonGpx = new Ext.Button({
		id: 'button_gpx',
		text: 'Télécharger le GPX',
		handler: function(){
			var listDownloadChecked = new Array();
			for (i=0;i<Ext.getCmp('grid_download').getSelectionModel().getSelections().length;i++){
				var id_cat = Ext.getCmp('grid_download').getSelectionModel().getSelections()[i].id;
				listDownloadChecked.push(id_cat);
			}
			Ext.Ajax.request({
				url: './php_geopyrenees/getGpx.php?listDownloadChecked='+listDownloadChecked,
				success: function (response){
					var res = Ext.util.JSON.decode(response.responseText);
					if (res.success == true){
						Ext.Msg.buttonText.cancel = 'Fermer';
						Ext.Msg.show({
							title: 'Téléchargement',
	                        msg: '<a href="./php_geopyrenees/downloadFile.php?file=' + res.file + '"><div style="text-decoration:underline;color:#000000">Cliquer ici pour enregistrer le fichier sur votre ordinateur.</div></a>',
							buttons: Ext.Msg.CANCEL,
	                        icon: Ext.Msg.INFO,
							minWidth: 400
						});
					}
					else{
						Ext.Msg.show({
							title: 'Attention',
							msg: '<div style="color:#000000">Veuillez sélectionner au moins une catégorie.</div>',
							buttons: Ext.Msg.OK,
							icon: Ext.Msg.WARNING,
							minWidth: 350
						});
					}
				}
			});
		}
	});
	
	
	var downloadListRecord = new Ext.data.Record.create([
		{name: 'id'},
		{name: 'cat'},
		{name: 'nb_elem', type: 'float'}
	]);
	
	var downloadList = new Ext.data.JsonStore({
		url: './php_geopyrenees/getDownloadList.php',
		root: 'categorie',
		id: 'id',
		fields: downloadListRecord,
		autoLoad: true
	});
	
	
	var typeListRecord = new Ext.data.Record.create([
		{name: 'id_type'},
		{name: 'lib_type'}
	]);
	
	var typeList = new Ext.data.JsonStore({
		url: './php_geopyrenees/getType.php',
		root: 'type',
		fields: typeListRecord,
		autoLoad: true
	});
	
	var tabchangeIndex = 0;
	
	var contentPanel = {
		id: 'content-panel',
		region: 'center',
		xtype: 'tabpanel',
		layoutOnTabChange: false,
		activeTab: 0,
		margins: '2 5 0 0',
		enableTabScroll: true,
		listeners: {
			tabchange: function(){
				if ((this.getActiveTab().getId() == 'tab2')) {
					this.getActiveTab().doLayout();
				}
				if (tabchangeIndex == 0){
					tabchangeIndex++;
				}
				else{
					if ((this.getActiveTab().getId() != 'tab6')) {
						Ext.getCmp('south').collapse();
					}
					else{
						Ext.getCmp('south').expand();
						if ((this.getActiveTab().getId() == 'tab2')) {
							alert('tab ajout');
							this.getActiveTab().doLayout();
						}
					}
				}
			}
		},
		items: [{
			id: 'tab0',
			layout: 'fit',
			title: 'Cartographie',
			iconCls: 'mapicon',
			items: {
				id:'carto',
				title: 'Cartographie',
				xtype: 'gmappanel',
				header: false,
				zoomLevel: 8,
				gmapType: 'map',
				//mapControls: ['GLargeMapControl','GMapTypeControl','GScaleControl','GOverviewMapControl'],
				mapControls: ['GLargeMapControl','GMapTypeControl','GScaleControl'],
				//mapControls: ['GMapTypeControl','GScaleControl','GOverviewMapControl'],
				mapConfOpts: ['enableScrollWheelZoom','enableDoubleClickZoom','enableDragging'],
				setCenter: {
					lat: 43,
					lng: 0.4827523076124293
				}
			}
		},{
			id: 'tab2',
			title: 'Ajouter des points d\'intérêt',
			iconCls: 'add',
			layout: 'absolute',
			autoScroll: true,
			items:[{
				border: false,
				x: 10,
				y: 10,
				contentEl: 'add-poi'
			},{
				id: 'form_addpoi',
				title: 'Renseignez les champs suivants',
				x: 20,
				y: 200,
				xtype: 'form',
				frame: true,
				labelWidth: 100,
				width: 350,
				height: 250,
				iconCls: 'add',
				defaultType: 'textfield',
				items: [{
					id: 'lib_objet',
					fieldLabel: 'Libellé ',
					name: 'lib_objet',
					allowBlank: false,
					anchor: '100%'
				},{
					id: 'type',
					fieldLabel: 'Catégorie ',
					xtype: 'combo',
					anchor: '100%',
					editable: false,
					emptyText: 'Sélectionner une catégorie',
					store: typeList,
					displayField: 'lib_type',
					valueField: 'id_type',
					hiddenName: 'id_type',
					mode: 'local',
					triggerAction: 'all',
					allowBlank: false
				},{
					id: 'url_bis_objet',
					fieldLabel: 'URL officielle ',
					name: 'url_bis_objet',
					vtype: 'url',
					anchor: '100%'
				},{
					id: 'lat_objet',
					fieldLabel: 'Latitude ',
					name: 'lat_objet',
					readOnly: true,
					anchor: '100%',
					allowBlank: false
				},{
					id: 'lng_objet',
					fieldLabel: 'Longitude ',
					name: 'lng_objet',
					readOnly: true,
					anchor: '100%',
					allowBlank: false
				},{
					id: 'alt_objet',
					fieldLabel: 'Altitude ',
					name: 'alt_objet',
					readOnly: true,
					xtype: 'hidden',
					anchor: '100%'
				},{
					id: 'email_createur_objet',
					fieldLabel: 'Votre email (*) ',
					name: 'email_createur_objet',
					vtype: 'email',
					anchor: '100%'
				},{
					id: 'newsletter',
	                xtype: 'radiogroup',
	                fieldLabel: 'Newsletter (*) ',
	                items: [
	                    {boxLabel: 'Oui', name: 'newsletter', inputValue: 1},
	                    {boxLabel: 'Non', name: 'newsletter', inputValue: 2, checked: true}
	                ]
            }],
				buttons: [
					{
						text: 'Enregistrer',
						handler: function(){
							Ext.getCmp('form_addpoi').getForm().submit({
								url: './php_geopyrenees/submitPOI.php',
								waitMsg: 'Enregistrement en base de données',
								waitTitle: 'Sauvegarde du point d\'intérêt',
								success: function(){
									Ext.MessageBox.show({
										title: 'Merci pour votre contribution !',
										msg: '<br>Le point d\'intérêt a été ajouté avec succès à la base de données.',
										buttons: Ext.MessageBox.OK,
										icon: Ext.MessageBox.INFO
									});
									Ext.getCmp('form_addpoi').getComponent('lib_objet').reset();
									Ext.getCmp('form_addpoi').getComponent('type').reset();
									Ext.getCmp('form_addpoi').getComponent('url_bis_objet').reset();
									Ext.getCmp('form_addpoi').getComponent('lat_objet').reset();
									Ext.getCmp('form_addpoi').getComponent('lng_objet').reset();
									Ext.getCmp('form_addpoi').getComponent('alt_objet').reset();
									Ext.getCmp('form_addpoi').getComponent('newsletter').reset();
								},
								failure: function(){
									Ext.MessageBox.show({
										title: 'Erreur !',
										msg: 'Veuillez renseigner les champs entourés de rouge et/ou renseigner la latitude ou la longitude.',
										buttons: Ext.MessageBox.OK,
										icon: Ext.MessageBox.ERROR
									});
								}
							})
						}
					},
					{
						text: 'Annuler',
						handler: function(){
							Ext.getCmp('form_addpoi').getComponent('lib_objet').reset();
							Ext.getCmp('form_addpoi').getComponent('type').reset();
							Ext.getCmp('form_addpoi').getComponent('url_bis_objet').reset();
							Ext.getCmp('form_addpoi').getComponent('lat_objet').reset();
							Ext.getCmp('form_addpoi').getComponent('lng_objet').reset();
							Ext.getCmp('form_addpoi').getComponent('alt_objet').reset();
							Ext.getCmp('form_addpoi').getComponent('newsletter').reset();
							Ext.getCmp('form_addpoi').getComponent('email_createur_objet').reset();
						}
					}
				]
			},{
				layout: 'fit',
				title: 'Déplacez le marqueur',
				iconCls: 'add',
				x: 400,
				y: 200,
				labelWidth: 75,
				width: 350,
				height: 280,
				items: {
					id:'carto2',
					title: 'Déplacez le marqueur',
					xtype: 'gmappaneladd',
					header: false,
					zoomLevel: 6,
					gmapType: 'map',
					mapControls: ['GMapTypeControl','GSmallMapControl'],
					mapConfOpts: ['enableScrollWheelZoom','enableDoubleClickZoom','enableDragging'],
					setCenter: {
						lat: 42.63843009593479,
						lng: 0.4827523076124293
					}
				}
			},{
				border: false,
				x: 0,
				y: 480,
				contentEl: 'facultatif'
			}]
		},{
			id: 'tab3',
			title: 'Télécharger les points d\'intérêt',
			iconCls: 'download',
			layout: 'absolute',
			autoScroll: true,
			items:[{
				border: false,
				x: 10,
				y: 10,
				contentEl: 'download-data'
			},{
				id: 'grid_download',
				title: 'Télécharger les points d\'intérêt',
				iconCls: 'download',
				xtype: 'grid',
				layout: 'fit',
				x: 20,
				y: 200,
				width: 500,
				autoHeight: true,
				store: downloadList,
				cm: new Ext.grid.ColumnModel([
					sm,
					{id:'cat',header: "Catégories", width: 278, sortable: true, dataIndex: 'cat'},
					{header: "Nombre d\'éléments", width: 200, sortable: true, dataIndex: 'nb_elem'}
				]),
				sm: sm,
				buttons: [buttonKmz,buttonGpx],
				buttonAlign:'center'
			}]
		},{
			id: 'tab6',
			title: 'A propos',
			iconCls: 'information',
			layout: 'absolute',
			autoScroll: true,
			items:[{
				border: false,
				x: 10,
				y: 10,
				contentEl: 'apropos-div'
			}]
		}
		]
	};
	
	Ext.getCmp('tree-panel').on({
		click: {
			delegate: "tr",
			fn: function(n) {
				//alert(this.getChecked());
				Ext.getCmp('content-panel').setActiveTab(0);
				n.getUI().toggleCheck();
				//alert('id du layer checked : '+n.id+'\nliste des layers checked : '+this.getChecked()+'\ntitle de la carte : '+Ext.getCmp('carto').title);
				/*if (n.isSelected() == true){
					//alert('déjà sélectionné');
					n.unselect();
				}
				else{
					//alert('pas sélectionné');
					n.select();
				}*/
				var sn = this.selModel.selNode || {}; // selNode is null on initial selection
		    	//if(n.leaf && n.id != sn.id){  // ignore clicks on folders and currently selected node 	
					
					Ext.getCmp('carto').addLayer();
					
		    		if(!detailEl){
		    			var bd = Ext.getCmp('details-panel').body;
		    			bd.update('').setStyle('background','#fff');
		    			detailEl = bd.createChild(); //create default empty div
		    		}
		    		detailEl.hide().update(Ext.getDom(n.id+'-details').innerHTML).slideIn('l', {stopFx:true,duration:.2});
		    	//}
			}
		},
		checkchange: {
			delegate: "tr",
			fn: function(n) {
				//alert(this.getChecked());
				Ext.getCmp('content-panel').setActiveTab(0);
				//alert('id du layer checked : '+n.id+'\nliste des layers checked : '+this.getChecked()+'\ntitle de la carte : '+Ext.getCmp('carto').title);
				var sn = this.selModel.selNode || {}; // selNode is null on initial selection
		    	//if(n.leaf && n.id != sn.id){  // ignore clicks on folders and currently selected node 	
					
					Ext.getCmp('carto').addLayer();
					
		    		if(!detailEl){
		    			var bd = Ext.getCmp('details-panel').body;
		    			bd.update('').setStyle('background','#fff');
		    			detailEl = bd.createChild(); //create default empty div
		    		}
		    		detailEl.hide().update(Ext.getDom(n.id+'-details').innerHTML).slideIn('l', {stopFx:true,duration:.2});
		    	//}
			}
		}
	});
	
	
    
	// This is the Details panel that contains the description for each example layout.
	var detailsPanel = {
		id: 'details-panel',
        title: 'Détails',
        region: 'center',
        bodyStyle: 'padding-bottom:15px;background:#eee;',
		autoScroll: true,
		html: '<p class="details-info">Lorsque vous sélectionnez des informations dans le navigateur, des informations s\'affichent ici.</p>'
    };
	
	// Finally, build the main layout once all the pieces are ready.  This is also a good
	// example of putting together a full-screen BorderLayout within a Viewport.
    new Ext.Viewport({
		layout: 'border',
		title: 'Ext Layout Browser',
		items: [{
			id: 'south',
			region: 'south',
			split: true,
			contentEl: 'partenaire',
			height: 90,
			minSize: 90,
			maxSize: 90,
			collapsible: true,
			collapsed: true,
			collapsedTitle: 'Financeurs et partenaires',
			plugins: new Ext.ux.collapsedPanelTitlePlugin(),
			title: 'Financeurs et partenaires',
			margins: '0 5 2 5'
        },{
			xtype: 'box',
			region: 'north',
			applyTo: 'header',
			height: 124
		},{
			layout: 'border',
	    	id: 'layout-browser',
	        region:'west',
	        border: false,
	        split:true,
			margins: '2 0 0 5',
	        width: 285,
	        minSize: 100,
	        maxSize: 500,
			items: [treePanel, detailsPanel]
		},
			contentPanel
		],
        renderTo: Ext.getBody()
    });

});
