Ext.Msg.minWidth = 300;
envoiAnnonce_callback
function envoiAnnonce_callback(callBack){
	
    if(callBack){
    	Ext.Msg.hide();
    	win_envoyer_annonce.hide();
    }else{
        Ext.Msg.alert('L\'annonce n\'a pas pu etre transfer&eacute;'); 
    }
}

// un tableau pour savoir si une annonce est deja ouverte dans une fenetre 
//en fonction de son idAnnonce
var annonceIsOpened = [];

// on garde une reference sur les objets AnnonceWindow avec leur idAnnonce 
// comme cl�
var annonceWindows = [];

AnnonceWindow = Ext.extend(Ext.Window, {
    // configurables
    // anything here can be configured from outside
    idAnnonce : '',
    ref : '',
    intitule : '',
    experience : '',
    ville : ''
}); // eo extend
 
// register xtype
Ext.reg('annoncewindowxtype', AnnonceWindow);

// une fonction qui ferme toutes les fenetres des annonces
function closeAllAnnonceWindows() {
	for (var i in annonceWindows) {
		if (typeof(annonceWindows[i]) !== 'function') {
			annonceWindows[i].close();
			annonceIsOpened[annonceWindows.idAnnonce] = false;
		}
	}
}
//--------------fenetre et elements pour envoyer  annonce par email---
//--------------------------------------------------------------------

var email_transfert =new Ext.form.TextField({
bodyStyle:'padding:5px',
blankText :'Email obligatoire',
allowBlank :false,
width: 185,
id:'email_transfert',
name:'email_transfert',
fieldLabel :'Email',
vtypeText: 'Votre adresse email n\'est pas valide',
vtype:'email',
msgTarget: 'side'		// Affiche une icone sur le cot� si erreur

});
var id_annonce = new Ext.form.Hidden({
	id:'id_annonce'});

var form_email_transfert = new Ext.FormPanel({
	bodyStyle:'padding:5px',
    monitorValid :true,
	//layout:'fit',
    //frame:true,
    width: 320,
    autoHeight:true,  items: [email_transfert,id_annonce]
});

var basic_form_email_transfert = new Ext.form.BasicForm();
basic_form_email_transfert.add(email_transfert);

var win_envoyer_annonce = new Ext.Window({
	bodyStyle:'padding:5px',
    constrainHeader :true,
    header: true,
    //layout      : 'fit',
    width       : 345,
    AutoHeight      : true,
    closeAction :'hide',
    plain       : true,
    modal:true,
    title :' ',
    cls         : 'win_annonce',
   
     buttonAlign :'center'
    ,items :[form_email_transfert]
    ,buttons:[{
           text: 'Valider',handler  : function(){                   
    	if(!basic_form_email_transfert.isValid()){
    		Ext.Msg.alert('L\'adresse email n\'est pas valide'); 
    	}else{
    		Ext.Msg.wait('Envoi de mail','Merci de patienter');
    		DWRProxy.envoiAnnonce(id_annonce.getValue().toString(),email_transfert.getValue().toString(),document.location.href.toString(),envoiAnnonce_callback);
    	}
            }
        },{
            text: 'Annuler',handler  : function(){                   
        	win_envoyer_annonce.hide();
        }
    }]


});



// on profite de l'appel DWRProxy pour renvoyer dans un tableau les
// elements necessaires de l'annonce
// on pourrait pousser plus loin en renvoyant directement un objet java Annonce 
function showAnnonce(annonceAsArray){
    var contenu_annonce = '<p style="padding: 20px 20px 0px;">'+annonceAsArray[5].toString()+'</p>'+

        '\n\
<div style="padding: 10px 20px 0px ;"><hr><div style="float:left;"><b>Localisation :</b> '+annonceAsArray[4].toString()+'</div><div style="float:right;"><b>Experience :</b> '+annonceAsArray[3].toString()+'</div><br><hr></div>'+
        '<div style="padding: 20px ;">'+
        '<table><tr><td> <img src="img/logo.gif" width="50%">  </td>'+
        '<td>'+
        'AVISTO - Ressources Humaines<br>'+
        '137, avenue du Gal Leclerc<br>'+
        '92340 Bourg la Reine<br><br></td></tr></table></div>';
 
    annonceWindows[annonceAsArray[0]] = new AnnonceWindow({ 
        constrainHeader :true,
        id          : annonceAsArray[1].toString(),
        renderTo    : 'td_contenu2',
        layout      : 'fit',
        width       : 550,
        autoHeight  : true,
        closeAction :'close',
        plain       : true,
        //modal     : true,
        title       : annonceAsArray[1].toString() + ' - ' + annonceAsArray[2].toString(),
        html        : contenu_annonce,
        buttonAlign : 'center',
        cls         : 'win_annonce',
        idAnnonce   : annonceAsArray[0].toString(),
        ref         : annonceAsArray[1].toString(),
    	intitule    : annonceAsArray[2].toString(),
   	 	experience  : annonceAsArray[3].toString(),
   		ville       : annonceAsArray[4].toString(),
        buttons     : [{
                  			text     : 'Postuler en ligne',
                			handler  : function(){
                	        		       showWindowPostuler(annonceWindows[annonceAsArray[0]]);
                              		   }
                      },
                      {
                			text     : 'Envoyer par mail ',
              			handler  : function(){
                    	  win_envoyer_annonce.setTitle('Envoyer par mail l\'annonce : \n' + annonceAsArray[1].toString());
                    	  id_annonce.setValue(annonceAsArray[0].toString());
                    	  win_envoyer_annonce.show();
                            		   }
                    }]
    });
	
    annonceWindows[annonceAsArray[0]].on('close', function() {  
        //on enleve de la liste des fenetres ouvertes
        annonceIsOpened[annonceAsArray[0]] = false;
    })
    
    annonceWindows[annonceAsArray[0]].on('show', function() {  
        //on ajoute � la liste des fenetres ouvertes
        annonceIsOpened[annonceAsArray[0]] = true;
    })
    
    annonceWindows[annonceAsArray[0]].show();
}

function showTopPanel() {
	/////////////////////////////////////////////////////////////////////////////////
	// GESTION DE LA GRILLE D'ANNONCES RESULTAT DE LA RECHERCHE
	/////////////////////////////////////////////////////////////////////////////////
	
    // le datastore utilis� pour l'affichage des annonces dans la grille
    var ds = new Ext.data.Store({
        proxy: new Ext.ux.data.DWRProxy({
            dwrFunction: DWRProxyAnnonce.getEntetesAnnoncesFiltrees,
            listeners: {
                         
                'beforeload': function (dataProxy, params) {
                    // setting the args that will get passed to the DWR function
                    // on passe dans l'ordre les villes coch�es dans un tableau
                    // l'exp�rience selectionn�e
                    // la reference (utilis�e en like)
                    var i=0;
                    var tab = [];
                    var index = 0;
                    for (i=0; i < villesCheckBoxes.items.length; ++i) {
                    	if (villesCheckBoxes.items.get(i).checked == true) {
	                    	tab[index] = villesCheckBoxes.items.get(i).getName();
	                    	index++;
	                    }	
	                }
 
                    params[dataProxy.loadArgsKey] = [tab, Ext.get('experienceRech').getValue(), referenceRech.getValue()];                               
                },
                'show': function() {
                    this.loadMask = new Ext.LoadMask(this.body, {msg:'Chargement des annonces'});                   
                },
                'loadexception': function() {
                    Ext.Msg.alert('Erreur de chargement des donn&eacute;es');
                },
                'load': function(thisDS, records, options) {
                	if(records.length == 0) {
                    	Ext.Msg.alert('Aucun r&eacute;sultat ne correspond aux crit&egrave;res saisis.');
                    }
                }                          				
            }
        }),
        
        reader: new Ext.data.ArrayReader({ totalProperty :'20' }  , Ext.data.Record.create([
            {name:'Ref'}, 
            {name:'Intitule'},
            {name:'Experience'},
            {name:'Ville'},
            {name:'Id'} ]
   	    ))
							
    });
		
			
		
	// le filter appliqu� sur la grille de resultats			
    var filters = new Ext.ux.grid.GridFilters({filters:[
            {type: 'string',  dataIndex: 'Ref'},
            {type: 'string',  dataIndex: 'Intitule'},
            {type: 'string', dataIndex: 'Experience'},
            {type: 'string', dataIndex: 'Ville'},
            {type: 'numeric', dataIndex: 'Id'}			
        ]});
			
	// le column model de la grille de resultats	
    var cm = new Ext.grid.ColumnModel([{
            dataIndex: 'Ref',              
            header: 'R&eacute;f&eacute;rence'
        }, { 
            dataIndex: 'Intitule',
            header: 'Intitul&eacute;'
        }, {
            dataIndex: 'Experience',
            header: 'Exp&eacute;rience'
        }, {
            dataIndex: 'Ville',
            header: 'Ville'
        }, {
            dataIndex: 'Id',
            header: 'Id',
            hidden:true
        }
    ]);
                        
    cm.defaultSortable= true
				
	// le gridpanel qui contient la grille et le bouton "nouvelle recherche"			
    var resultatsPanel = new Ext.grid.GridPanel({                    
        id: 'resultatsPanel',
        ds: ds,
        cm: cm,
        enableColLock: false,
        loadMask: true,
        height:220 ,
        width:760,
        stripeRows:true,
        autoExpandColumn :1
    });
           
    resultatsPanel.on("rowclick", function(){
        // create the window on the first click and reuse on subsequent clicks
        var sel = resultatsPanel.getSelectionModel().getSelected();
        var idAnnonce = sel.data.Id.toString();         
        var ref = sel.data.Ref;
         
        // si la fen�tre de l'annonce est d�ja ouverte on la ram�ne au premier plan
        // au lieu d'en ouvrir une nouvelle
        if (annonceIsOpened[idAnnonce] != 'undefined'  && annonceIsOpened[idAnnonce] == true) {
        	Ext.WindowMgr.bringToFront(annonceWindows[idAnnonce]);
        } else {
       		DWRProxy.getContenuAnnonce(idAnnonce, showAnnonce);
        }
    });   
    
    
   	
   	//////////////////////////////////////////////////////////////////////////
   	// LES ELEMENTS DU FORMULAIRE DE RECHERCHE D'ANNONCES
   	//////////////////////////////////////////////////////////////////////////
   	
	// NB le checkboxgroup des villes est initialis� dynamiquement dans accueil.jsp
   	var villesCheckBoxes = new Ext.form.CheckboxGroup({
                xtype: 'checkboxgroup',
                id:'villesCheckBoxes',
                allowBlank: true,
                fieldLabel: 'Villes',
                itemCls: 'x-check-group-alt',
                width: 600,
                items: villesCheckBoxesItems,
                columns: 3});
   	
   	
    var experienceRech = new Ext.form.ComboBox({
    	id:'experienceRech',
    	fieldLabel: 'Exp&eacute;rience',
    	name: 'experienceRech',
    	allowBlank :true,
    	editable : false,
    	store: new Ext.data.Store({
        	proxy: new Ext.ux.data.DWRProxy({
            dwrFunction: DWRProxyAnnonce.getListeExperiences,
            listeners: {
                'beforeload': function(dataProxy, params){
                    // setting the args that will get passed to the DWR function
                    params[dataProxy.loadArgsKey] = []; 
                },
                'loadexception': function() {
                    Ext.Msg.alert('Erreur de chargement de la liste des exp&eacute;riences');
                }
            }
        	}),
        	reader: new Ext.data.ArrayReader({}, Ext.data.Record.create([
                {name: 'idExp'},
                {name: 'libelleExp'}
            ]))
    	}),
    	displayField: 'libelleExp',
    	valueField:'idExp',
    	queryParam:'query',
    	value:'               ' // on ne peut pas mettre une simple chaine vide comme valeur par d�faut!!!
	});
	
	   
    var referenceRech = new Ext.form.TextField({
        allowBlank :true,
        width: 200,
        id:'reference',
        name:'reference',
        fieldLabel :'R&eacute;f&eacute;rence'
    });

        
    // le panel qui contient le formulaire de recherche des annonces
    var recherchePanel = new Ext.FormPanel({
        id : 'recherchePanel',
        monitorValid :false,
        fileUpload :true,        
        bodyStyle:'padding:10px 10px 0',
        width: 760,
        height:170,
        autoScroll : true,
        items: [villesCheckBoxes, experienceRech, referenceRech],

        buttons: [ {id:'btnRech',
                text: 'Rechercher',handler  : function() {
                    resultatsPanel.show();
                    ds.load({params:{start: 0, limit: 100}});
               		
                }
            }
            ]
    });
    
   
    
    
    // le panel qui comprend le filtre de recherche et la grille
    // de r�sultats d'annonces a tour de role
    var topPanel = new Ext.Panel({
    	id: 'top',
    	bodyStyle:'padding:10px 10px 10px 10px; margin:0px',
        width: 790,
        bodyBorder: false,
    	border:false,
        items: [recherchePanel, new Ext.Panel({
        	width: 10,
        	height:30,
        	bodyBorder: false}),
        resultatsPanel]
    });
    	
    topPanel.render('td_contenu2');
    // TODO experienceRech.store.load({params:{start: 0, limit: 100}});
    resultatsPanel.hide();
}

function showWindowPostuler(annonceWin) {    
    /////////////////////////////////////////////////////////////////////////////////////
    // LES ELEMENTS DU FORMULAiRE POUR POSTULER A UNE ANONCE
    /////////////////////////////////////////////////////////////////////////////////////
    
    var nom =new Ext.form.TextField({
        blankText :'Nom obligatoire',
        allowBlank :false,
        id:'nom',
        name:'nom',
        fieldLabel :'Nom',
        msgTarget: 'side'		// Affiche une icone sur le cot� si erreur
    });
    var prenom =new Ext.form.TextField({
        blankText :'Pr&eacute;nom obligatoire',
        allowBlank :false,
        id:'prenom',
        name:'prenom',
        fieldLabel :'Pr&eacute;nom',
        msgTarget: 'side'		// Affiche une icone sur le cot� si erreur
    });

    var email =new Ext.form.TextField({
        blankText :'Email obligatoire',
        allowBlank :false,
        width: 200,
        id:'email',
        name:'email',
        fieldLabel :'Email',
        vtypeText: 'Votre adresse email n\'est pas valide',
        vtype:'email',
        msgTarget: 'side'		// Affiche une icone sur le cot� si erreur
   
    });
    var telephone =new Ext.form.TextField({
        blankText :'T&eacute;l&eacute;phone obligatoire',
        allowBlank :false,
        id:'telephone',
        name:'telephone',
        fieldLabel :'T&eacute;l&eacute;phone',
        msgTarget: 'side'		// Affiche une icone sur le cot� si erreur
    });
    var cv =new Ext.form.TextField({
        blankText :'CV obligatoire',
        allowBlank :false,
        id:'cv',
        name:'cv',
        fieldLabel :'CV',
        inputType : 'file',
        msgTarget: 'side'		// Affiche une icone sur le cot� si erreur
    });

    var commentaire  = new Ext.form.TextArea({
        id:'commentaire',
        width :700,
        name:'commentaire',
        fieldLabel: 'Commentaire',
        height:'200'
    });
  

    var basicFormPostuler = new Ext.form.BasicForm();
    basicFormPostuler.add(commentaire,cv,nom,prenom,email,telephone);
 
        
    var formPostuler = new Ext.FormPanel({
        monitorValid	: true,
        fileUpload		: true,
        method			: 'POST',
        frame			: true,
        bodyStyle		: 'padding:5px 5px 0',
        width			: 750,
        height			: 300,
        autoScroll		: true,
    
        items			: [{
                				layout	: 'column',
                				items	: [{
                        						columnWidth:.5,
                        						layout: 'form',
                        						items: [nom, prenom]
                    					   },{
                       							columnWidth:.5,
                        						layout: 'form',
                        						items: [telephone,email]
                    					  }]
            			   },
            			   commentaire,
            			   cv],

        buttons: [ {
            
                text: 'OK',handler  : function(){//teste si tous les champs sont valide
                    if(!basicFormPostuler.isValid()){
                        Ext.Msg.alert('Merci de renseigner les champs correctement');  
                    }
                    else{
                        url = root + '/Upload?id=' + annonceWin.idAnnonce + //'&ref='+ encodeURIComponent(annonceWin.ref) +'&intitule='+encodeURIComponent(annonceWin.intitule)+
                        		'&nom='+encodeURIComponent(nom.getValue()) + '&prenom='+encodeURIComponent(prenom.getValue())+'&tel='+encodeURIComponent(telephone.getValue())+'&email='+encodeURIComponent(email.getValue())+'&commentaire='+encodeURIComponent(commentaire.getValue())+'&ville='+encodeURIComponent(annonceWin.ville);                
                  		 
                        formPostuler.form.submit(
                        {url:url,
                        waitMsg: 'Merci de patienter ...',
                        success : function(form, action){
                               win_postuler.close();
	                           annonceWin.close();
                               // TODO enlever  de la liste des fenetres ouvertes    
                            },
                         failure:function(form, action){
                     			obj = Ext.util.JSON.decode(action.response.responseText); 
                                if (obj.errors.reason) {
                                	Ext.Msg.alert('Une erreur s\'est produite', obj.errors.reason);
                                } else {
                                	Ext.Msg.alert('Une erreur s\'est produite', obj.errors);
                                }
                                	
                            }
                        });         
                    }
                }
            },{
                text: 'Annuler',handler  : function(){ 
                    win_postuler.close();
                }
            }]
    });

    // la fen�tre contenant le formulaire pour postuler    
    var win_postuler  = new Ext.Window({
        id : 'win_postuler',
        constrainHeader :true,
        layout      : 'fit',
        width       : 850,
        height      : 420,
        plain       : true,
        modal       : true,
        cls         : 'win_annonce',
        items       : [formPostuler]
    });
    
    win_postuler.setTitle(annonceWin.ref + ' - ' + annonceWin.intitule);
   	win_postuler.show();
   	
}
