

Ext.onReady(function(){


    var myPageSize = 10;

    var fm = Ext.form, Ed = Ext.grid.GridEditor;

    var urlSite = 'http://www.bruded.org';
	//var urlSite = 'http://91.121.90.64';
		
    Ext.QuickTips.init();
    
    function formatBoolean(value){
        return value ? 'Yes' : 'No';  
    }
	
    function formatEtat(value){
        return value==1 ? 'en ligne' : 'hors ligne';
    }
	
	 
    function renderTopic(value, p, record){
        return String.format('<b><img src="/images/pictos/petits/'+record.data["picto"]+'" alt="" />  {0}</b>', value, record.data['pro_desc']);
	// return String.format('<b><img src="/images/pictos/petits/'+record.data["picto"]+'" alt="" />  {0}</b><br />{1}', value, record.data['pro_desc']);
    }
	
    function renderDate(value){
        return String.format(value.dateFormat('M j, Y'));
    }
    
    function renderCat(value){
	
		var out="";
		var arrayCat = value.split('-');
		
		if(arrayCat.length>2){
			
		   for(i=0;i<=arrayCat.length;i++)
 			out += (i != arrayCat.length) ? "<strong>"+arrayCat[i]+'</strong> ' : "<br /><i>"+arrayCat[i]+"</i>";
	
		}
		else if(arrayCat.length>1 && arrayCat.length<3)
		{
			out = "<strong>"+arrayCat[0]+"</strong><br /><i>"+arrayCat[1]+"</i>";	
		}
		else		
		{
		
			out = "<strong>"+value+"</strong>";
		}
	
		return out;

   }


	
    var cm = new Ext.grid.ColumnModel([{
           id: 'id_projet',
           header: "Identify",
           dataIndex: 'id_projet',
           width: 150,
           hidden: true
        },{
		header:'Désignation',
		dataIndex:'pro_nom',
		width:300,
		renderer:renderTopic
				
	},
	{
		header:"Catégorie",
		dataIndex:"CAT_LIB",
		width:180,
		renderer:renderCat
	},
	{
		header:"Collectivit&eacute; / Etablissement",
		dataIndex:"etablissement",
		width:205
	},
	{
		header:"picto",
		dataIndex:"picto",
		width:205,
		hidden:true
	}	
	]);
      
    cm.defaultSortable = true;
		  
 /****************
 *
 * CREATION DU DATAGRID
 *
 *****************/

    var ds = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
           url: urlSite+'/pages/listingProjets.php'
        }),
        reader: new Ext.data.JsonReader({
            root: 'projets',
            totalProperty: 'totalcount',
            id: 'id_projet'
        }, [
            {name: 'id_projet'},
            {name: 'pro_nom'},
	    {name: 'CAT_LIB'},
            {name: 'pro_desc'},
    /*	    {name: 'pro_date_deb'},
	    {name: 'pro_date_fin'},	*/
	    {name: 'etablissement'},
	    {name: 'picto'}
        ]),
        remoteSort: false
    });
	    ds.setDefaultSort('id_projet', 'ASC');

    var grid = new Ext.grid.Grid('editor-grid2', {
        ds: ds,
        cm: cm,
        selModel: new Ext.grid.RowSelectionModel({singleSelect:false}),
        enableColLock:false,
		trackMouseOver:true,
		autoHeight:true,
		height:80 ,
		loadMask:true ,
waitMsg:'Chargement'
	});

    var layout = Ext.BorderLayout.create({
        center: {
            panels: [new Ext.GridPanel(grid)]
        }
    }, 'grid-panel2');

       grid.render();
	   grid.on('cellclick', showProjet); 


//	var gridFoot = grid.getView().getFooterPanel(true);
	
	 // add a paging toolbar to the grid's footer
/*    var paging = new Ext.PagingToolbar(gridFoot, ds, {
        pageSize: myPageSize,
        displayInfo: true,
        displayMsg: 'total {2} projets. Actuellement {0} - {1}',
        emptyMsg: "Aucun résultat à afficher"
    });
*/	
	/************************************************************
	 *  header panel 
	 ************************************************************/
	var gridHead = grid.getView().getHeaderPanel(true);
	var tb = new Ext.Toolbar(gridHead);

	
	/* Categorie */
	
	var storeCat = new Ext.data.JsonStore({
		url: urlSite+'/pages/listingCat.php',
		root: 'cat',
		fields: ['cat_lib','cat_code']
          });	


    var combo = new Ext.form.ComboBox({
        store: storeCat,
	id:'cat_code',
        displayField:'cat_lib',
        typeAhead: true,
        triggerAction: 'all',
        emptyText:'Type de projet...',
	loadingText:'Chargement...',
        selectOnFocus:true,
        width:155,
        resizable:true,
	valueField: 'cat_code'
    });

   	
    combo.on('select', function() { 
        comboEta.reset();
	ds.load( {params:{ cat: combo.getValue() }});
      
    });
	
	
	/* Etablissement */
	
    var storeEta = new Ext.data.JsonStore({
	url: '/pages/listingEtablissement.php',
	root: 'etablissement',
	fields: ['eta_id','eta_nom']
    });	


    var comboEta = new Ext.form.ComboBox({
        store: storeEta,
		id:'eta_id',
        displayField:'eta_nom',
        typeAhead: true,
        triggerAction: 'all',
        emptyText:'Etablissement...',
	loadingText:'Chargement...',
        selectOnFocus:false,
        width:185,
        resizable:true,
	valueField: 'eta_id'
    });
	
    comboEta.on('select', function() { 
        combo.reset();
	ds.load( {params:{ eta: comboEta.getValue() }});
    });



       





	/* Rechercher dans projets */

	var txtSearch = new Ext.form.TextField({
        fieldLabel: 'Chercher dans les projets',
        name: 'search',
        allowBlank:false,
		validateOnBlur :true
    });
	ds.on("load",function(){ });
	
	txtSearch.setValue('Mot clef...');
	
/*	txtSearch.on('focus',function(){
		txtSearch.setValue('');
	});
*/
	var validerSearch = new	Ext.Toolbar.Button({
		//cls: 'x-btn-icon',
        text: 'Valider',
		pressed:false,
        //menu: menu,
        tooltip: 'Valider le formulaire'
	});
	
	validerSearch.on('click',function(){ 
		ds.load( {params:{ val: txtSearch.getValue() }});
	});

	var clearBtn = new Ext.Toolbar.Button({
        text: 'Raffra&icirc;chir',
	pressed:false,
        //menu: menu,
        tooltip: 'Reinitialiser'
	});
	
	clearBtn.on('click',function(){ 
           combo.reset();
           comboEta.reset();
	   ds.load();
	});
	
	tb.add('<strong>Filtres :</strong> ');
	tb.addField(combo);	
	tb.addSeparator();
	tb.addField(comboEta);
	tb.addSeparator();
	tb.addField(txtSearch);
	tb.addButton(validerSearch);
        tb.addButton(clearBtn);
 
	// chargement DataStore


    // si on a choisi un etablissement en cliquant sur une fiche projet (bton: "projets de la collectivité")

   if(selectEta!=""){
	ds.load( { params:{eta:selectEta} });
   }else if(selectCat!=""){
	ds.load( {params:{ cat: selectCat}});
    }else
    {
	  ds.load();
   } 
	
	

	

   /************************************************************
    * Action - Acces fiche projet
    ************************************************************/	
      
    function showProjet()
	{

       	var m = grid.getSelections();
		var idProjet = m[0].get('id_projet');
//		var url = "/pages/infoCollectivite.php?idCollect="+idCollect+"&dossier="+dossier+"&rub="+idRub;
		var url="/index.php?rub="+idRub+"&p="+idPage+"&id_projet="+idProjet;
   
		//alert(url);
/*		new Ajax.Request(url, 
		{   method: 'get', 
		    onSuccess: function(request) {
		    var pageDest = request.responseText; //http://91.121.90.64/"+dossier+"/collectivites-adherentes-developpement-durable/
			alert(pageDest);
			window.document.href(pageDest);
//			window.location.href(pageDest);			
			//alert(Request.responseText) ; 
		    },
		    onFaillure : function(request){
			alert("erreur:"+request.responseText);
		    }
		}); 
*/	
		
	//	var url = dossier+"/"+urlPage+","+idRub+","+idPage+".html";
	//	var url = '/index.php?page=projets&id_projet='+m[0].get("id_projet"); 
	
		window.location.replace(url);
	}
 


    function addClickOutsideEvent(grid) {
    	if (!grid.events.clickoutside) {
	    	grid.addEvents({"clickoutside": true});
	    }
	    if (!Ext.grid.Grid.prototype.handleClickOutside) {
	    	Ext.grid.Grid.override({
	    		handleClickOutside: function(e) {
		            var p = Ext.get(e.getTarget()).findParent(".x-grid-container");
		            if (p != this.container.dom) {
				        this.fireEvent("clickoutside", e, grid);
		            }
	    		}
	    	});
	    }
        Ext.get(document.body).on("click", grid.handleClickOutside, grid);
    }

  


  
   	Ext.form.Field.prototype.msgTarget = 'side';
   	Ext.form.Field.prototype.height = 20;
	Ext.form.Field.prototype.fieldClass = 'text-field-default';
	Ext.form.Field.prototype.focusClass = 'text-field-focus';
	Ext.form.Field.prototype.invalidClass = 'text-field-invalid';

 
  
    var libel = new Ext.form.TextField({
            fieldLabel: 'Libell&eacute;',
            name: 'libel',
            allowBlank:false
    });
    	
	var code = new Ext.form.TextField({
            fieldLabel: 'Code',
            name: 'code',
            allowBlank:false
    });
	var abrev = new Ext.form.TextField({
            fieldLabel: 'Abr&eacute;viation',
            name: 'abrev',
            allowBlank:false
    });
	var code = new Ext.form.TextField({
            fieldLabel: 'Code',
            name: 'code',
            allowBlank:false
    });
	var catStore = new Ext.data.JsonStore({
			   url: '/modules/pdts/action_pdts.php?action=sscat',
           root: 'sscat',
           fields: ['id','libel']
    });	
	

   var cat = new Ext.form.ComboBox({
	hiddenName:'cat',
        store: catStore,
        displayField:'libel',
	typeAhead: true,
	fieldLabel:'Sous cat&eacute;gorie ',
        triggerAction: 'all',
        emptyText:'Categorie...',
	loadingText:'Chargement...',
        selectOnFocus:true,
        width:200,
	name:'cat',
	valueField: 'id'
    });
	
	
	var storeData = [['1', 'En ligne'], ['0', 'Hors ligne'] ]; 
        
	  var store = new Ext.data.SimpleStore({
        fields: ['id', 'libel'],
        data : storeData
	});
	
	
    var etat = new Ext.form.ComboBox({
	hiddenName:'etat',
        store: store,
        displayField:'libel',
        typeAhead: true,
		fieldLabel:'Etat',
//        mode: 'local',
        triggerAction: 'all',
        emptyText:'Etat...',
		loadingText:'Chargement...',
        selectOnFocus:true,
        width:135,
		name:'etat',
		valueField: 'id'
    });
	
    var form_instance_create2 = new Ext.form.Form({
        labelAlign: 'right',
        url:'modules/pdts/action_pdts.php?action=createAccount'
    });

    form_instance_create2.column({width: 430, labelWidth:120, style:'margin-left:8px;margin-top:8px'});
    form_instance_create2.fieldset(
        {id:'desc', legend:'Remplissez les champs'},
        libel,
		etat,
		cat,
		abrev,
		code
	);
	

    
});
