/**
 * @brief	Gestion des interventions !
 * @author	Renan
 * @date	29/08/2011
 * @to		06/09/2011	Renan correction parcours des tableaux pour google Chrome (utilisation de la methode hasOwnProperty() )
 * @version 1
 */
function Intervention( o )
{
	this.id				= 0;
	this.delaiDepart	= 0;
	this.maxMateriel	= 0;
	this.maxVehicule	= 0;
	this.minLevel		= 0;
	
	this.elementByPage	= 15;	// nomre de vignette a afficher par page !
	this.selectCat		= null;
	this.listeMat		= null;
	this.selectVeh		= null;
	this.listeVeh		= null;
	this.selectRen		= null;
	this.listeRen		= null;
	this.typeActif		= null;	// materiel ou vehicule
	this.catActif		= null;

	/* ~constructeur~ */
	for( var i in o){
		this[i] = o[i];
	}
	
	var obj = this;
	
	/**
	 * METHODE : Intervenir (partir en intervention) !
	 */
	this.intervenir = function(){

		// Récupération des véhicules
		var mesVehicules = 0;
		$('#addInterVehicule > div').not('.addInter').each(function(){
			if( mesVehicules == 0 )
				mesVehicules = $(this).attr('id');
			else
				mesVehicules += ',' + $(this).attr('id');
		});
		
		// Récupération des véhicules
		var monRenfort = 0;
		if( $('input[name=renfort]:checked').length > 0 )
		{
			$('#addInterRenfort > div').not('.addInter').each(function(){
				if( monRenfort == 0 )
					monRenfort = $(this).attr('id');
				else
					monRenfort += ',' + $(this).attr('id');
			});
		}
		
		
		// Récupération du matériel
		var monMat = 0;
		$('#addInterMateriel > div').not('.addInter').each(function(){
			if( monMat == 0 )
				monMat = $(this).attr('id');
			else
				monMat += ',' + $(this).attr('id');
		});
		
		
		if( mesVehicules == 0 ){
			jAlert('Il te faut au moins un véhicule pour partir en intervention !');
		}
		else
		{
			// Son du camion de pompier !
			//playSoundFlash( 'secteur18_sound', 'departIntervention' );
			
			// On indique que le départ se fait !
			$('#menu-intervention').html('En route ...');
			
			$.post('/fr/game/pages/intervention/ajax.php',	{ 	action:	'start', 
																id:		this.id,
																veh:	mesVehicules,
																mat:	monMat,
																ren:	monRenfort
															},function(){											
				$('#depart-container').html('<p class="ok">Vos véhicules viennent de partir sur les lieux de l\'intervention !</p>');
			});
			
		}
		
	}
	
	
	/**
	 * METHODE : Préparation avant le départ en intervention (sélection du matériel, véhicules, ...)
	 */
	this.choice = function( time )
	{

		// Récupération de ce que le joueur a !
		this.preloadItems();
		
		$.post('/fr/game/pages/intervention/ajax.php', { action:'choice', id:this.id, time:time }, function( data ){
			
			$('#depart-container').html( data[0] );

			// Gestion du délai
			if (time == false) {
				$('#ingame-intervention > a').html('Départ : <span id="timerDepartMenu"></span>');
				getTime(obj.delaiDepart, 'timerDepart');
				getTime(obj.delaiDepart, 'timerDepartMenu');
			}
			else
				getTime( time , 'timerDepart');

			// Récupération des sélections déjà faites par le joueur !
			if( data[1]!=null && data[1].length>0 )
			{
				for( var i in data[1] )
				{
					obj.loadMem( 'vehicule',  data[1][i]);
				}
			}

			if( data[2]!=null && data[2].length>0 )
			{
				for( var i in data[2] )
				{

					obj.loadMem( 'materiel', data[2][i] );
				}
			}


		}, 'json' );
	}
	
	
	/**
	 * METHODE : demander du renfort! 
	 */
	this.renfort = function(){
		
		if( $('#tab_renfort > #select_renfort').length == 0 )
		{
			$('#tab_renfort').append('<div id="select_renfort" class="cacher"><div id="addInterRenfort" class="addInterContainer wrapper"><div class="addInter infobulle" title="Ajouter un véhicule en renfort">+</div></div>');
		}
		
		// La case n'est pas cochée !
		if( $('input[name=renfort]:checked').length == 0 )
			$('#select_renfort').fadeOut( 'fast' );
		else
			$('#select_renfort').fadeIn( 'fast' );
	}
	
	
	/**
	 * METHODE : Mise à jour de la quantité d'un objet/véhicule utilisé !
	 * @param {Object} id
	 * @param {Object} val
	 */
	this.set_utilise = function( id, val ){
		
		var cherche = '';

		if( this.typeActif == 'vehicule' )
		{
			cherche = this.listeVeh;
		}
			
		else if( this.typeActif == 'renfort' )
			cherche = this.listeRen;
		else
			cherche = this.listeMat;


		// Parcours des éléments !
		for( var e in cherche )
		{
			if(cherche.hasOwnProperty(e)) {
				if (parseInt(cherche[e]['id']) == id) {
					// +1
					if (val == 1) {
						if (cherche[e]['utilise'] < cherche[e]['quantite']) {
							cherche[e]['utilise']++;
							return true;
						}
					}
					// -1
					else {
						if (cherche[e]['utilise'] > 0) {
							cherche[e]['utilise']--;
							return true;
						}
					}
					break;
				}
			}	
		}
		return false;
	}
	
	/**
	 * Récupération de ce que possède le joueur !
	 */
	this.preloadItems = function(){

		// Vérification que ça n'a pas déjà été fait !
		if( this.listeMat == null || this.listeVeh == null )
		{
			$.post('/fr/game/pages/intervention/ajax.php', { action:'loadElement'}, function( data  ){
						
				// Création de la liste déroulante pour les catégories de Matériel
				obj.selectMat = '<select name="selectCatMat" onchange="objIntervention.getElement(this.value, 1, false);">';
				for( var j in data[0] )
				{
					if (data[0].hasOwnProperty(j)) {
						obj.selectMat += '<option value="' + data[0][j]['id'] + '">' + data[0][j]['nom'] + '</option>';
					}
				}
				obj.selectMat += '</select>';
				
				// Création de la liste déroulante pour les catégories de Véhicules ET renfort
				obj.selectVeh = '<select name="selectCatVeh" onchange="objIntervention.getElement(this.value, 1, false);">';
				obj.selectRen = '<select name="selectCatRen" onchange="objIntervention.getElement(this.value, 1, false);">';
				for( var j in data[2] )
				{
					if (data[2].hasOwnProperty(j)) 
					{
						obj.selectVeh 	+= '<option value="' + data[2][j]['id'] + '" ' + ((data[2][j]['id'] == 1) ? 'selected' : null) + '>' + data[2][j]['nom'] + '</option>';
						obj.selectRen 	+= '<option value="' + data[2][j]['id'] + '" ' + ((data[2][j]['id'] == 1) ? 'selected' : null) + '>' + data[2][j]['nom'] + '</option>';
					}
				}
				obj.selectRen += '</select>';
				obj.selectVeh += '</select>';				
				
				// Mémorisation des différents véhicules et matériel dont on dispose (pour ne pas avoir à refaire de requete ajax)
				obj.listeMat 		= data[1];
				obj.listeVeh 		= data[3];
				obj.listeRen		= data[4];
			}, 'json');
		}
	}


	
	/**
	 * Affichage du formulaire pour ajouter un véhicule ou du matériel ou du renfort
	 */
	this.addElement = function( type )
	{
		this.loadElement( type, 1 ); 
	}
	
	/** 
	 * Affichage de la popup "Ajout d'un véhicule/matériel"
	 */
	this.loadElement = function( type, categorie )
	{
		var popup 		= '';
		this.typeActif	= type;
		this.catActif	= categorie;

		// Affichage du formulaire :
		if( this.typeActif == 'vehicule' )
		{
			popup += '<p>Sélectionne un véhicule que tu souhaites faire intervenir !<br/><em>Note : seuls tes véhicules prêt à partir sont affichés ici !</em></p>';
			popup += '<p align="center">Véhicules pour : ' + this.selectVeh + '</p>';
		}
		else if( this.typeActif == 'materiel' ){
			popup += '<p>Sélectionne le matériel que tu souhaites faire intervenir !</p>';
			popup += '<p align="center">Matériel pour : ' + this.selectMat + '</p>';
		}
		else{
			popup += '<p>Sélectionne les véhicules en renfort que tu souhaites faire intervenir !</p>';
			
			if( this.listeRen.length == 0 )
				popup += '<p class="ok">Aucun véhicules de ton alliance n\'est actuellement disponible ou tu ne fais pas parti d\'une alliance !</p>';
			else			
				popup += '<p align="center">Véhicules pour : ' + this.selectRen + '</p>';
		}
		
		var view	= this.getElement( categorie, 1, true );
			
		popup += view;
		contenuPopupAjax( popup );
	}
	
	/**
	 * Affichage des élément d'une catégorie dans la popup
	 */
	this.getElement = function( categorie, page, retour )
	{
		var	n			= 0;
		var view 		= '';
		var startView 	= (page-1) * this.elementByPage
		var pageTotal	= 0;

		//--- Affichage des véhicules (selon la catégorie choisie)
		if (this.typeActif == 'vehicule') 
		{
			for( var e in this.listeVeh )
			{
				if (this.listeVeh.hasOwnProperty(e)) 
				{
					var cat = this.listeVeh[e]['cat'].split(',');
					for (var j in cat) {
						if (cat.hasOwnProperty(j)) 
						{
							if (cat[j] == categorie) {
								// affichage si page courante !
								if (n >= startView && n < (startView + this.elementByPage)) {
									view += '<div class="infobulle ' + (this.listeVeh[e]['utilise'] == 1 ? 'utilise' : '') + '" from="' + this.typeActif + '::' + this.catActif + '" id="' + this.listeVeh[e]['id'] + '" title="' + this.listeVeh[e]['desc'] + '<br/><em>Carburant : ' + this.listeVeh[e]['essence'] + '%</em>"><img src="/fr/static/images/vehicules/miniature/' + this.listeVeh[e]['img'] + '" style="width:'+this.listeVeh[e]['width']+'px; height:'+this.listeVeh[e]['height']+'px;"/><div class="genSubtitle">' + this.listeVeh[e]['nom'] + (this.listeVeh[e]['perso'] != null ? ' ' + this.listeVeh[e]['perso'] : '') + (this.listeVeh[e]['utilise'] == 1 ? '<br/><em>sélectionné</em>' : '') + '</div></div>';
								}
								n++;
							}
						}
					}
				}
			}
			
			if( n == 0 )
				view += '<p class="warning" align="center">Tu ne possèdes aucun véhicule de cette catégorie prêt à partir en intervention !</p>';
		}
		
		//--- Affichage du matériel disponible (selon la catégorie)
		else if (this.typeActif == 'materiel'){
			for( var e in this.listeMat )
			{
				if (this.listeMat.hasOwnProperty(e)) {
					if (categorie == this.listeMat[e]['cat']) {
						// affichage si page courante !
						if (n >= startView && n < (startView + this.elementByPage)) {
							view += '<div class="infobulle ' + (this.listeMat[e]['utilise'] == this.listeMat[e]['quantite'] ? 'utilise' : '') + '" from="' + this.typeActif + '::' + this.catActif + '" id="' + this.listeMat[e]['id'] + '" title="' + this.listeMat[e]['nom'] + '<br/><b>Disponible :</b> ' + (this.listeMat[e]['quantite'] - this.listeMat[e]['utilise']) + '"><div align="center"><img src="/fr/static/images/materiel/' + this.listeMat[e]['img'] + '" style="width:100px; height:100px;"></div><div class="genSubtitle2">' + this.listeMat[e]['nom'] + '</div></div>';
						}
						n++;
					}
				}	
			}
			
			if( n == 0 )
				view += '<p class="warning" align="center">Tu ne possèdes pas de matériel appartenant à cette catégorie !</p>';
		}
		
		//--- Affichage des véhicules en renfort (selon la catégorie choisie)
		else{
			if (this.listeRen.length > 0) {
				for (var e in this.listeRen) {
					if (this.listeRen.hasOwnProperty(e)) 
					{
						var cat = this.listeRen[e]['cat'].split(',');
						for (var j in cat) 
						{
							if (cat.hasOwnProperty(j)) 
							{
								if (cat[j] == categorie) 
								{
									// affichage si page courante !
									if (n >= startView && n < (startView + this.elementByPage)) 
									{
										view += '<div class="infobulle ' + (this.listeRen[e]['utilise'] == 1 ? 'utilise' : '') + '" from="' + this.typeActif + '::' + this.catActif + '" id="' + this.listeRen[e]['id'] + '" title="' + this.listeRen[e]['desc'] + '"><img src="/fr/static/images/vehicules/miniature/' + this.listeRen[e]['img'] + '" style="width:'+this.listeRen[e]['width']+'px; height:'+this.listeRen[e]['height']+'px;" ><div class="genSubtitle">' + this.listeRen[e]['nom'] + (this.listeRen[e]['utilise'] == 1 ? '<br/><em>sélectionné</em>' : '') + '</div></div>';
									}
									n++;
								}
							}
						}
					}
				}
				
				if( n == 0 )
					view += '<p class="warning" align="center">Ton alliance ne possède aucun véhicule de ce type prêt à partir en intervention !</p>';
			}
			
		}
		
		// Pagination
		pageTotal = Math.ceil( n / this.elementByPage );
		var pagination;
		if( pageTotal > 1) {
			pagination =	'<a href="#/intervention/feuille_depart" onclick="objIntervention.getElement( \''+categorie+'\', '+(page>1 ? page-1:1)+', false);">Précédente</a>';
			pagination += ' - <b>' + page + '</b>/' + pageTotal + ' - ';
			pagination +=	'<a href="#/intervention/feuille_depart" onclick="objIntervention.getElement( \''+categorie+'\', '+(page==pageTotal ? pageTotal:page+1)+', false);">Suivante</a>';
		}
		else
			pagination = '';
			
		if( retour )
		{
			return '<div class="viewGenInter wrapper" id="listeInterElement">' + view + '</div><p class="wrapper" align="center" id="paginationInter">' + pagination + '</p>';
		}
		else
		{
			$('#listeInterElement').html( view );
			$('#paginationInter').html( pagination );
		}
			
	}

	/**
	 * Mémorisation des véhicules/matériels choisis !
	 */
	this.memorise = function(){
		
		var veh = '';
		var mat = '';

		$('#addInterVehicule > div').not('.addInter').each(function(){
			veh += $(this).attr('id') + ',';
		});

		$('#addInterMateriel > div').not('.addInter').each(function(){
			mat += $(this).attr('id') + ',';
		});

		// Envoi de la requête ajax !
		$.post('/fr/game/pages/intervention/ajax.php', { action:'memorise_select', v:veh, m:mat });
	}

	/**
	 * Retourne la vignette d'un véhicule/matériel selon son Id !
	 */
	this.viewVignette = function (type, id ){
		if ( type  == 'vehicule') 
		{
			for( var e in this.listeVeh )
			{
				if (this.listeVeh.hasOwnProperty(e)) 
				{
					var cat = this.listeVeh[e]['cat'].split(',');
					for (var j in cat) 
					{
						if (cat.hasOwnProperty(j)) 
						{
							if( this.listeVeh[e]['id'] == id )
							{
								return '<div class="infobulle ' + (this.listeVeh[e]['utilise'] == 1 ? 'utilise' : '') + '" from="' + this.typeActif + '::' + this.catActif + '" id="' + this.listeVeh[e]['id'] + '" title="' + this.listeVeh[e]['desc'] + '<br/><em>Carburant : ' + this.listeVeh[e]['essence'] + '%</em>"><img src="/fr/static/images/vehicules/miniature/' + this.listeVeh[e]['img'] + '" style="width:'+this.listeVeh[e]['width']+'px; height:'+this.listeVeh[e]['height']+'px;"/><div class="genSubtitle">' + this.listeVeh[e]['nom'] + (this.listeVeh[e]['perso'] != null ? ' ' + this.listeVeh[e]['perso'] : '')  + '</div></div>';
							}
						}
					}
				}
			}
			
			if( n == 0 )
				view += '<p class="warning" align="center">Tu ne possèdes aucun véhicule de cette catégorie prêt à partir en intervention !</p>';
		}
		else if ( type  == 'materiel')
		{
			for( var e in this.listeMat )
			{
				if (this.listeMat.hasOwnProperty(e)) 
				{
					if ( this.listeMat[e]['id'] == id ) 
					{
						return '<div class="infobulle ' + (this.listeMat[e]['utilise'] == this.listeMat[e]['quantite'] ? 'utilise' : '') + '" from="' + this.typeActif + '::' + this.catActif + '" id="' + this.listeMat[e]['id'] + '" title="' + this.listeMat[e]['nom'] + '<br/><b>Disponible :</b> ' + (this.listeMat[e]['quantite'] - this.listeMat[e]['utilise']) + '"><div align="center"><img src="/fr/static/images/materiel/' + this.listeMat[e]['img'] + '" style="width:100px; height:100px;"></div><div class="genSubtitle2">' + this.listeMat[e]['nom'] + '</div></div>';
					}
				}	
			}
		}

		return false;
	}

	/**
	 * Affichage des véhicules/matériels présélectionnés
	 */
	this.loadMem = function( type, id )
	{
		this.typeActif = type;

		if( this.set_utilise( id, 1) == true )
		{
			var nombreVerif = 0;
			var typeVerif 	= '';
			var levelVerif 	= 0;
			switch (this.typeActif) 
			{
				case 'vehicule':
					nombreVerif = this.maxVehicule;
					typeVerif 	= 'addInterVehicule';
					break;
				case 'materiel':
					nombreVerif = this.maxMateriel;
					typeVerif = 'addInterMateriel';
					break;
			}
		
			// Ajoute le véhicule dans la liste !			
			var preview = this.viewVignette( type, id );
			$('#' + typeVerif + ' .addInter').before( preview  );
			
			//gestion affichage du bouton +
			var n = parseInt($('#' + typeVerif + ' > div').length) - 1;
			if (n >= nombreVerif) 
				$('#' + typeVerif + ' > div.addInter').hide();
		}

		this.typeActif = null;

		return true;
	}
	
}

function afficheRenfort()
{
	if ( $('input[name=demandeRenfort]:checked').length == 1 )
		$('#afficherDemandeRenfort select').attr('disabled',false);
	else 
		$('#afficherDemandeRenfort select').attr('disabled',true);			
}


/**
 * @brief	Fonctions utilisées pour générer une scène d'intervention
 * @author	Renan
 * @since	06/06/11
 * @version	1
 */
function GenerateurIntervention( o )
{
	this.etape 				= 1;
	this.maxMateriel		= 0;
	this.maxVehicule		= 0;
	this.minLevel			= 0;
	this.selectCat			= null;
	this.listeMat			= null;
	this.selectVeh			= null;
	this.listeVeh			= null;
	this.typeActif			= null;	// materiel ou vehicule
	this.catActif			= null;
	this.mode 				= 'create';
	
	/* Editeur de scène */
	this.item 				= null;
	this.background 		= null;
	this.categorie 			= null;
	this.zindex				= 1;
	this.idNum				= 1;
	this.eActive			= null;
	this.id					= 0;
	this.tab_item			= new Array();
	
	/* Mémorisation des données du formulaire */
	this.form_type 			= null;
	this.form_stype 		= null;
	this.form_reussite 		= null;
	this.form_scenario 		= null;
	this.form_scenariotech 	= null;
	this.form_idscene 		= null;

	/* ~constructeur */
	for( var i in o){
		this[i] = o[i];
	}
	
	
	/**
	 * Gérer les différentes étapes de la création d'une intervention !
	 */
	this.next = function(){
		
		var msg_err = '';
		
		// 1 => 2
		if( this.etape == 1 )
		{
			var type 		= parseInt($('select[name=typeInter] option:selected').val());
			var stype		= parseInt($('select[name=typeInterPrecision] option:selected').val());
			var scenario	= $('textarea[name=scenario]').val();
			var scenario_tech = $('textarea[name=scenariotech]').val();
			var reussite	= $('input[name=scenario_ok]').val();
			
			if( type == 0 )
				msg_err += '- Choisir un type d\'intervention !<br/>';
			
			if( scenario == '' )
				msg_err += '- Expliquer le scénario !<br/>';
			
			if( scenario.length < 50 )
				msg_err += '- Le scénario doit avoir au moins 50 caractères !<br/>';
			
			if( reussite.length > 0 && reussite.length < 25 )
				msg_err += '- La phrase de réussite doit avoir au moins 25 caractères !<br/>';
			
			if (this.id == 0) // est ce que la scène a été choisie/créée
			{
				if( $('#genInterScene-elements .elementInter').length > 0 )
				{
					msg_err += '- Enregistrer ta scène d\'intervention !<br/>';
				}
				else
					msg_err += '- Choisir ou Créer une scène d\'intervention !<br/>';
			}
			if( msg_err.length > 0 )
				jAlert('Pour continuer la création de ton intervention, corrige ces erreurs :<br/><br/>' + msg_err);
			else{
				
				// Mémorisation
				this.form_type 		= type;
				this.form_stype 	= stype;
				this.form_scenario 	= scenario;
				this.form_scenariotech = scenario_tech;
				this.form_reussite 	= reussite;
				this.form_idscene 	= this.id;
				
				// Affichage de l'étape 2
				this.etape = 2;
				var tab_etape2 	= '<table width="800" align="center" id="formInter">';
				tab_etape2		+='<tr><td><h3>Sélection des véhicules :</h3></td></tr>';
				tab_etape2		+='<tr><td><div>Ajoute le(les) véhicule(s) qui devront intervenir pour réussir cette intervention ! <em>(maximum : ' + this.maxVehicule + ')</em></div><div id="addInterVehicule" class="wrapper"><div class="addInter infobulle" title="Ajouter un véhicule">+</div></div></td></tr>';
				tab_etape2		+='<tr><td><h3>Sélection du matériel :</h3></td></tr>';
				tab_etape2		+='<tr><td><div>Ajoute le matériel supplémentaire à emmener pour mener à bien cette intervention ! <em>(maximum : ' + this.maxMateriel + ')</em></div><div id="addInterMateriel" class="wrapper"><div class="addInter infobulle" title="Ajouter du matériel">+</div></div></td></tr>';
				tab_etape2		+='<tr><td><h3>Options et Informations :</h3>';
				tab_etape2		+='<p><label><input type="checkbox" name="selectRenfort" value="1" onchange="objInter.getInterLevel(false);" /> Déclencher du renfort au cours de l\'intervention</label></p>';
				tab_etape2		+='<p>Tu peux voir ci-dessous la difficulté de l\'intervention que tu viens de configurer, ainsi que le niveau minimum requis pour qu\'elle apparaisse.</p>';
				tab_etape2		+= this.getInterLevel( true );
				tab_etape2		+='</td></tr>';
				tab_etape2		+='<tr><td>&nbsp;</td></tr>';
				tab_etape2		+='<tr><td colspan="2" align="center"><p><a class="nextStep" href="#/intervention/generateur" onclick="objInter.next(); return false;">Proposer mon intervention</a></p></td></tr>';
				tab_etape2		+='</table>';
				
				$('#content > h2').html( 'Etape 2 : Sélection des moyens matériels');
				$('table#formInter').replaceWith( tab_etape2 );
				
				//clic le +
				$('.addInter').die('click').live('click', function(){
					if( $(this).parent().attr('id') == 'addInterVehicule')
					{
						popup('Ajout d\'un nouveau véhicule !');
						objInter.addElement('vehicule');
					}
					else{
						popup('Ajout d\'un nouveau matériel !');
						objInter.addElement('materiel');
					}
				});
			}
		}
		
		// Enregistrement
		else if( this.etape == 2 )
		{
			// Controle des données
			var nVehicule 	= parseInt( $('#addInterVehicule > div').not('.addInter').length );
			var nMateriel 	= parseInt( $('#addInterMateriel > div').not('.addInter').length );
			
			if( nVehicule == 0  )
				msg_err += '- Sélectionne au moins 1 véhicule !<br/>';
			
			if( nVehicule > this.maxVehicule  )
				msg_err += '- Tu as trop de véhicule, supprimes-en !<br/>';
			
			if( nMateriel > this.maxMateriel  )
				msg_err += '- Tu as trop de matériel, supprimes-en !<br/>';
			
			if( msg_err.length > 0 )
				jAlert('Pour proposer ton intervention, tu dois d\'abord corriger ces erreurs :<br/><br/>' + msg_err);
			else{
				jConfirm('Souhaites-tu vraiment proposer cette intervention ?', 'Attention', function(e){
					if( e == true ){
						
						// Récupération des véhicules
						var mesVehicules = 0;
						$('#addInterVehicule > div').not('.addInter').each(function(){
							if( mesVehicules == 0 )
								mesVehicules = $(this).attr('id');
							else
								mesVehicules += ',' + $(this).attr('id');
						});
						
						// Récupération du matériel
						var monMat = 0;
						$('#addInterMateriel > div').not('.addInter').each(function(){
							if( monMat == 0 )
								monMat = $(this).attr('id');
							else
								monMat += ',' + $(this).attr('id');
						});
						
						// Enregistrement en BDD !
						$.post('/fr/game/pages/intervention/generateur.ajax.php', { 	action:	'saveInter',
																			t:		objInter.form_type,
																			st:		objInter.form_stype,
																			sc:		escape(objInter.form_scenario),
																			tech:	escape(objInter.form_scenariotech),
																			r:		escape(objInter.form_reussite),
																			img:	objInter.form_idscene,
																			veh:	mesVehicules,
																			mat:	monMat,
																			ren:	($('input[name=selectRenfort]:checked').length==1 ? true:false),
																			niv:	objInter.minLevel
																		}, function( data  ){
							
							var tab_etape3 	= '<table width="800" align="center" id="formInter">';
							
							if( data == true )
							{
								tab_etape3		+='<tr><td><p class="ok" align="center">Félicitations,<br/><br/> l\'intervention a bien été créé et a été transmise à notre équipe pour qu\'elle la valide.<br/>Nous te remercions pour ta participation !<br/></p></td></tr>';
								$('#content > h2').html( 'Etape 3 : Validation de l\'intervention ');
							}
							else{
								tab_etape3		+='<tr><td><p class="ok" align="center">Une erreur est survenue durant l\'enregistrement ! L\'intervention n\'a pas pu être enregistrée correctement !</p></td></tr>';
								$('#content > h2').html( 'Erreur !');
							}
							
							tab_etape3		+='<tr><td><p align="center"><a href="#/caserne" onclick="pageLoad(\'/fr/game/#/caserne\');" class="bouton"><b>Revenir à ma Caserne</b></a></p></tr></td>';
							tab_etape3		+='</table>';
							
							$('table#formInter').replaceWith( tab_etape3 );
							
						}, 'json');
					}
				});
			}
			
		}
	}
	
	
	/**
	 * Affiche la difficulté de l'intervention actuelle
	 */
	this.getInterLevel = function( create ){
		var step 			= 15;
		var max  			= 500;
		var level			= 0;
		var minLevel		= 0;
		var difficult 		= 0;
		var difficultText = null;
		var html = '<div id="levelInter-container"><div><b>Difficulté :</b> <span id="interDifficult">{d}</span> - <b>Niveau minimum  :</b> <span id="levelMin">{n}</span></div><div id="viewInterLevel">{level}</div></div>';
		
		// récupération niveau minimum
		$('#addInterVehicule > div').not('.addInter').each(function(){
			var n = parseInt( $(this).attr('level') );
			if( n > minLevel )
				minLevel = n;
		});
		this.minLevel = minLevel;
		
		// ajout matériel
		difficult += parseInt( $('#addInterMateriel > div').not('.addInter').length );		// poids matériel = 2
		difficult += parseInt( $('#addInterVehicule > div').not('.addInter').length ) * 2;	// poids véhicule = 3
		
		
		difficult += $('input[name=selectRenfort]:checked').length==1 ? 4:0;	// poids renfort = 4;
		
		level = parseInt(step * difficult);
		if( level > max )
			level = max;
		
		if( level < 100 )		difficultText = 'Très facile';
		else if( level < 200 )	difficultText = 'Facile';
		else if( level < 300 )	difficultText = 'Normal';
		else if( level < 400 )	difficultText = 'Moyen';
		else					difficultText = 'Difficile';
		
		if( create )
		{
			html = html.replace( '{d}', difficultText );
			html = html.replace( '{n}', minLevel );
			html = html.replace( '{level}', '<div class="levelInter"><div class="levelInterActif" style="width:' + level + 'px;"></div></div>');
			return html;
		}
		else{
			$('.levelInterActif').animate({ width : level + 'px'});
			$('#interDifficult').html( difficultText );
			$('#levelMin').html( minLevel );
		}
	}
	
	
	/**
	 * Affichage du formulaire pour ajouter un véhicule ou du matériel
	 */
	this.addElement = function( type )
	{
		var popup 		=  null;
				
		// Chargement du matériel et des véhicules possibles (si pas déjà fait) !
		if( this.listeMat == null || this.listeVeh == null )
		{
			$.post('/fr/game/pages/intervention/generateur.ajax.php', { action:'loadElement'}, function( data  ){
				
				// Création de la liste déroulante pour les catégories de Matériel
				objInter.selectMat = '<select name="selectMat" onchange="objInter.getElement(this.value, false);">';
				for( var j in data[0] ){
					if (data[0].hasOwnProperty(j)) {
						objInter.selectMat += '<option value="' + data[0][j]['id'] + '">' + data[0][j]['nom'] + '</option>';
					}
				}
				objInter.selectMat += '</select>';
				
				// Création de la liste déroulante pour les catégories de Véhicules
				objInter.selectVeh = '<select name="selectMat" onchange="objInter.getElement(this.value, false);">';
				for( var j in data[2] ){
					if (data[2].hasOwnProperty(j)) {
						objInter.selectVeh += '<option value="' + data[2][j]['id'] + '" ' + ((data[2][j]['id'] == 1) ? 'selected' : null) + '>' + data[2][j]['nom'] + '</option>';
					}
				}
				objInter.selectVeh += '</select>';
				
				// Mémorisation des différents véhicules et matériel dont on dispose (pour ne pas avoir à refaire de requete ajax)
				objInter.listeMat 		= data[1];
				objInter.listeVeh 		= data[3];
				
				// Création de la popup pour sélectionner un matériel/véhicule
				objInter.loadElement( type, 1 );
			}, 'json');
		}
		else
			this.loadElement( type, 1 ); 
	}
	
	
	/** 
	 * Affichage de la popup "Ajout d'un véhicule/matériel"
	 */
	this.loadElement = function( type, categorie )
	{
		var popup 		= '';
		this.typeActif	= type;
		this.catActif	= categorie;
		
		// Affichage du formulaire :
		if( this.typeActif == 'vehicule' )
		{
			popup += '<p>Sélectionne un véhicule que tu souhaites intégrer à ton intervention !</p>';
			popup += '<p align="center">Véhicules pour : ' + this.selectVeh + '</p>';
		}
		else{
			popup += '<p>Sélectionne le matériel que tu souhaites intégrer à ton intervention !</p>';
			popup += '<p align="center">Matériel pour : ' + this.selectMat + '</p>';
		}
		
		var view	= '<div class="viewGenInter wrapper" id="listeInterElement">';
			view 	+=this.getElement( categorie, true );
			view 	+='</div>';
			
		popup += view;
		contenuPopupAjax( popup );
	}
	
	/**
	 * Affichage des élément d'une catégorie dans la popup
	 */
	this.getElement = function( categorie, retour )
	{
		var	n		= 0;
		var view 	= '';
		
		// Affichage des véhicules (selon la catégorie choisie)
		if (this.typeActif == 'vehicule') 
		{
			for( var e in this.listeVeh )
			{
				if (this.listeVeh.hasOwnProperty(e)) {
					var cat = this.listeVeh[e]['cat'].split(',');
					for (var j in cat) {
						if (cat.hasOwnProperty(j) && cat[j] == categorie) {
							view += '<div class="infobulle" id="' + this.listeVeh[e]['id'] + '" level="' + this.listeVeh[e]['niv'] + '" title="' + this.listeVeh[e]['desc'] + '<br/><em>(à partir du niveau ' + this.listeVeh[e]['niv'] + ')</em>"><img src="/fr/static/images/vehicules/miniature/' + this.listeVeh[e]['img'] + '" style="width:'+this.listeVeh[e]['width']+'px; height:'+this.listeVeh[e]['height']+'px;" /><div class="genSubtitle">' + this.listeVeh[e]['nom'] + '</div></div>';
							n++;
						}
					}
				}
			}
			
			if( n == 0 )
				view += '<p class="warning" align="center">Aucun véhicules n\'appartient a cette catégorie !</p>';
		}
		
		// Affichage du matériel disponible (selon la catégorie)
		else{
			for( var e in this.listeMat )
			{
				if( this.listeMat.hasOwnProperty(e) && categorie == this.listeMat[e]['cat'] ){
					view 	+= '<div class="infobulle" id="' + this.listeMat[e]['id'] + '" title="' + this.listeMat[e]['nom'] + '"><div align="center"><img src="/fr/static/images/materiel/' + this.listeMat[e]['img'] + '" style="width:100px; height:100px;"></div><div class="genSubtitle2">' + this.listeMat[e]['nom'] + '</div></div>';
					n++;
				}	
			}
			
			if( n == 0 )
				view += '<p class="warning" align="center">Aucun matériel n\'appartient a cette catégorie !</p>';
		}
		
		if( retour )
			return view;
		else
			$('#listeInterElement').html( view );
	}
	
	/**
	 * Sélection type d'intervention
	 */
	this.selectType = function(){
		
		var categorie 	= $('select[name=typeInter] option:selected').val();
		$.post('/fr/game/pages/intervention/generateur.ajax.php', { action:'loadTypeInter', cat:categorie, page:1, id:this.id }, function( data ){
			
			$('select[name=typeInterPrecision]').html( data[0] );
			$('#imgTypeInter > img').attr('src', data[3]);
			
			// Si l'onglet "choisir une scène existante" est active !
			if( objInter.item == "scene" )
			{
				$('#scene-container > h4 span').html( $('select[name=typeInter] option:selected').html() );
			
				var cat = parseInt( $('select[name=typeInter] option:selected').val() );
				$('#scene-listeImage').html( data[1] );
				
				// Génération de la pagination si nécessaire !
				if( data[2] > 1 )
				{
					var pagination = '';
					
					for( var i = 1; i<=data[2]; i++ ){
						if( i > 1 )
							pagination += ' - ';
						pagination += '<span ' + (i == 1 ? 'class="active"':'' ) + '>' + i + '</span>';
					}
					
					$('#paginationGenInter').html( pagination );
				}
				
				// Suppression de la pagination si nécessaire
				else if( data[2] <= 1 && parseInt($('#paginationGenInter > span').length) > 0 )
				{
					$('#paginationGenInter ').html('');
				}
			}
			
		}, 'json');
	}
	
	this.loadPageImage = function( page ){
		var categorie 	= $('select[name=typeInter] option:selected').val();
		$.post('/fr/game/pages/intervention/generateur.ajax.php', { action:'loadPageImage', cat:categorie, page:page, id:this.id }, function( data ){
			
			$('#scene-listeImage ').html( data );
			
			
		}, 'json');
	}
	
	
	/**
	 * ONGLET : Créer une nouvelle scène d'intervention 
	 */
	this.start = function()
	{
		this.item = 'new';
		
		$('#generateInter_choice > span').removeClass('actif');
		$('#generateInter_choice_new').addClass('actif');
		
		this.background = null;
		
		$.post('/fr/game/pages/intervention/generateur.ajax.php', { action:'initScene' }, function( e ){
			
			$('#genInterScene').html( e[0] ).hide().fadeIn('fast');
			objInter.tab_item = e[1];
			objInter.showItems( 'paysage' );	
		}, 'json' );
	}
	
	/**
	 * ONGLET : Sélection d'une scène existante !
	 */
	this.selectScene = function(){
		
		if( this.item != 'scene' )
		{
			this.item  = 'scene';
			
			$('#generateInter_choice > span').removeClass('actif');
			$('#generateInter_choice_select').addClass('actif');
			
			$.post('/fr/game/pages/intervention/generateur.ajax.php', { action: 'selectScene', cat:parseInt($('select[name=typeInter] option:selected').val()) }, function(data){
				
				$('#genInterScene').html( data ).hide();
				objInter.selectType();
				$('#genInterScene').fadeIn('fast');
				
			}, 'json');
		}
	}
	
	/**
	 * Sélection d'une catégorie (affiche du carrousel)
	 */
	this.showItems = function( categorie ){
		
		var title;
		var a;
		
		if (this.background != null || categorie == 'paysage' ) {
			this.categorie = categorie;
			$('#genInterScene-menu > span').removeClass('actif');
			$('#genInterScene-menu > span[type=' + this.categorie + ']').addClass('actif');
			
			if( typeof(this.tab_item[categorie]) != 'undefined' )
			{
				var carrousel 	= '<div id="genPop-container"><h3><center>' + this.tab_item[categorie]['title'] + '</center></h3>';
				carrousel		+='<div class="carrousel" id="carrousel-genInter"><a href="#" class="prev"><img src="/fr/static/images/genInter/previous.png"></a>';
				carrousel		+='<div class="interieur-carrousel"><div class="items">';
				
				for( var e in this.tab_item[categorie] )
				{
					if( this.tab_item[categorie].hasOwnProperty(e) &&  e != 'rep' && e!= 'title'  )
					{
						a 	= this.tab_item[categorie][e]['img'].split('/');
						title 	= a[(a.length-1)];
						title	= title.substr( 0, (title.length-4) );
						carrousel 	+= '<div class="item infobulle" title="' + title + '" ><img src="' + this.tab_item[categorie][e]['img'] + '" style="width:' + this.tab_item[categorie][e]['largeur'] + 'px; height:' + this.tab_item[categorie][e]['hauteur'] + 'px;" type="' + categorie + '" alt="' + this.tab_item[categorie][e]['alt'] + '" rel="' + this.tab_item[categorie][e]['rel'] + '" align="absmiddle" ></div>';
					}
				}
				
				carrousel 		+= '</div></div><a href="#" class="next"><img src="/fr/static/images/genInter/next.png"></a></div></div>';
				
				
				$('#genPop-container').remove();
					
				// Création de la popup de fond
				$('#genInterScene-elements').append('<div id="genPop" style="z-index:' + (this.zindex + 1000) + '"></div>');
				$('#genPop-container').hide().fadeIn();
				
				// Clic sur un item = on place l'élément !
				$('.carrousel .item').die('click').live('click', function(){
					objInter.placeItem(objInter.categorie, $(this).children().attr('src'), $(this).children().attr('alt'), $(this).children().attr('rel'));
				});
				
				// On affiche les données
				$('#genInterScene-elements').append( carrousel );
				
				// Activation du Carrousel !
				Carrousel('carrousel-genInter', 100, 100, 5);
				
				// On met le tout au premier plan !
				$('#genPop-container').css('z-index', Math.round(this.zindex + 1001));
			}
		}
	}
	
	/**
	 * On dépose un élément sur la scène
	 * @param {Object} categorie
	 * @param {Object} img
	 */
	this.placeItem = function( categorie, img, alt, rel ){
		
		// Changement du décor
		if( categorie == 'paysage' )
		{
			$('#genInterScene-elements-container').css('background-image', "url('" + img + "')");
			this.background = img;
			this.closeItem();
		}
		else{
			var element = '<div style="z-index:' + this.zindex + '; top:0px; left:0px" id="gi' + this.idNum + '" class="elementInter" rel="100"><img src="' + img + '" alt="' + alt + '" rel="' + rel + '"/></div>';
			$('#genInterScene-elements').append( element );
			
			$(".elementInter").draggable();
			this.closeItem();
			
			// on passe au zindex suivant (et à l'id suivant) !
			this.zindex++;
			this.idNum++;
		}
	}
	
	/**
	 * Fermeture de la popup des items
	 */
	this.closeItem = function(){
		$('#genInterScene-container #genPop-container, #genPop').fadeOut('fast', function(){
					$(this).remove();
		});
	}
	
	
	/**
	 * Retirer un élément de la scène
	 */
	this.remove = function(){
		
		// 1 - Suppresion de l'élément
		var z = $('#' + this.eActive ).css('z-index');
		$('#' + this.eActive ).fadeOut('fast', function() { $(this).remove(); });
		this.eActive = null;
		$('#genInter-itemSelect > span').html( 'Aucun' );
		
		// 2 - Regénération des zIndex des éléments suivant (pour toujours garder un zIndex optimum
		var debutNavig 	= true;
		var finNavig 	= false;
		var zEnCours	= 0;
		do{
			if( debutNavig == true ) // sélection du premier élément !
			{
				var $monDiv = $('#genInterScene-elements > div.elementInter:first').attr('id');
				debutNavig = false;
			}
			else 
				$monDiv = $('#' + $monDiv).next().attr('id');
			
			// détection du dernier élément (permet de stopper le traitement)
			if ($monDiv == $('#genInterScene-elements > div.elementInter:last').attr('id')) 
				finNavig = true;
		
			zEnCours = parseInt($('#' + $monDiv).css('z-index'));
			
			if( zEnCours > z )
				$('#' + $monDiv).css('z-index', (zEnCours-1));
		}
		while( finNavig == false )
		
		
		// mise à jour du prochain zIndex !
		this.zindex = this.zindex-1;
	}
	
	
	/**
	 * Placement des élément dessus/dessous
	 */
	this.position = function(choix){
		if(this.eActive!=null) //modification que si un objet a été choisi
		{
			var zActuel 	= parseInt($('#'+this.eActive).css('z-index')); //zindex actuel de l'objet sélectionné (fixe)
			
			var zDerriere 	= 1;			// le zIndex existant qui se trouve juste avant (par défault 0)
			var zDevant 	= this.zindex;	// le zIndex existant qui se trouve juste après (par défault très grand)
			var idDerriere 	= null;			// id de l'objet ayant le zIndex actif juste derière
			var idDevant 	= null;			// id de l'objet ayant le zIndex actif juste devant
			
			var zEnCours 	= 0;			// le zIndex que l'on parcours (temporaire)
			var debutNavig 	= true;			// indique si l'on commence la navigation des objets dans la cage ou non (0 ou 1)
			var finNavig 	= false;		// indique si on a terminer la navigation des objets dans la cage ou non (0 ou 1)
			
			//recherche le zIndex juste devant et/ou juste derrière
			do{
				if( debutNavig == true ) // sélection du premier élément !
				{
					var $monDiv = $('#genInterScene-elements > div.elementInter:first').attr('id');
					debutNavig = false;
				}
				else 
					$monDiv = $('#' + $monDiv).next().attr('id');
				
				// détection du dernier élément (permet de stopper le traitement)
				if ($monDiv == $('#genInterScene-elements > div.elementInter:last').attr('id')) 
					finNavig = true;
					
				zEnCours = parseInt($('#' + $monDiv).css('z-index'));
				
				if( zActuel-1 == zEnCours )
				{
					idDerriere 	= $monDiv;
					zDerriere 	= $('#' + $monDiv).css('z-index');
				}
				
				if( zActuel+1 == zEnCours )
				{
					idDevant 	= $monDiv;
					zDevant 	= $('#' + $monDiv).css('z-index');
				}
				
				// On interrompt si on a déjà tout ce qu'il nous faut !
				if( idDevant!=null && idDerriere!=null  )
					finNavig = true;
			}
			while(finNavig == false)
			
			//action
			switch(choix){
				case 'devant':
								//possible que si l'on est pas au zMax
								if(zActuel < (this.zindex-1))
								{
									$('#'+this.eActive).css('z-index',(zDevant));
									$('#'+idDevant).css('z-index',parseInt(zActuel));
								}
								break;
				
				case 'derriere':
								//possible que si l'on est pas au zMin
								if(zActuel > 1)
								{
									$('#'+this.eActive).css('z-index',(zDerriere));
									$('#'+idDerriere).css('z-index',parseInt(zActuel));
								}
								break;
			}
		}
	}
	
	
	
	/**
	 * Modification du zoom du produit sélectionnés !
	 * > 3 niveau de zoom 60%, 80% et 100%
	 */
	this.zoom = function(zoom){
		if (this.eActive != null) {
			var dimObj 			= null;
			var dimObjEnCours 	= new Array();
			var wObj 			= null;
			var hObj 			= null;
			var xObj 			= null;
			var yObj 			= null;
			
			/* récupération des dimensions de l'objet en % */
			var rel 	= parseInt( $('#'+this.eActive).attr('rel') );
			
			/* récupération des dimensions de l'image originale en pixel */
			dimObj 			= $('#' + this.eActive + ' > img ').attr('rel');
			dimObjEnCours 	= dimObj.split('-');
			wObj 			= parseInt(dimObjEnCours[0]);
			hObj 			= parseInt(dimObjEnCours[1]);
			
			/* on agrandit ou rétrécit l'image en fonction de ce que l'on souhaite */
			if (zoom == 'retrecir' && rel > 40)
				rel -= 10;
			else if (zoom == 'agrandir' & rel <100)
				rel += 10;
			else false;
			
			//zoom en cours !
			$('#' + this.eActive).attr('rel', rel);
			
			/* on redimensionne comme on a souhaité */
			$('#' + this.eActive + ',#' + this.eActive + '> img').css('width', Math.floor(wObj * (rel / 100)) + 'px');
			$('#' + this.eActive+ ',#' + this.eActive + '> img').css('height', Math.floor(hObj * (rel / 100)) + 'px');
			
		}
	}
	
	/**
	 * Enregistrement de la scène !
	 */
	this.saveScene = function()
	{
		var elements = null;
		var rel;
		var zoom;
		var zindex;
		var x;
		var y;
		var img;
		var bg;
		
		if (this.background!=null)
		{
			// Ajout effet FadeIn
			$('#scene-container').append('<div id="scene-save">Enregistrement en cours,<br/>Veuillez patienter ...</div>');
			$('#scene-save').css('height', $('#scene-container').height() + 'px').css('z-index', (parseInt(this.zindex) + 1000));
			$('#scene-save').hide().fadeIn();
			
			bg 	= this.background.replace( '/fr/static/images/genInter/', '' );
			$('#genInterScene-elements > .elementInter').each(function(index){
				
				x 		= formatPx( $(this).css('left') );
				y 		= formatPx( $(this).css('top') );
				zindex 	= $(this).css('z-index');
				zoom 	= $(this).attr('rel');
				img		= $(this).children().attr('src');
				img 	= img.replace( '/fr/static/images/genInter/', '' );
				
				if( elements == null )
					elements = img + '|' + zindex + '|' + zoom + '|' + x + '|' + y;
					
				elements += ',' + img + '|' + zindex + '|' + zoom + '|' + x + '|' + y;
			});
			
			
			// On enregistre la scène comme une image applatie
			$.post('/fr/game/pages/intervention/generateur.ajax.php', { action: 'saveScene', background:(bg), scene:(elements), id:this.id 	}, function(data){
				
				
				if (data == false) {
					fadeOutSave();
					jAlert('Le décor principal n\'est pas valide ! Sélectionne un paysage depuis l\'onglet "Paysage"');
				}
				else {
					objInter.id = data;
					
					$('#scene-save').html('La scène a bien été enregistrée !');
					setTimeout( "objInter.fadeOutSave()", 800 );
				}
				
			}, 'json');
			
		}
	}
	
	
	this.fadeOutSave = function(){
		$('#scene-save').fadeOut(function(){
				$(this).remove();
		});
	}
	
	
	this.stats = function(){
		$.post('/fr/game/pages/intervention/generateur.ajax.php', { action : 'stats' }, function( data ){
			
			 $('#content_edit_inter').html( data );
			 
			 // Animation de la barre de progression des stats !
			if( $('#statsInter').length > 0 )
			{
				$('#statsInter > div.statsInter').each(function(){
					$(this).animate({ width : $(this).attr('pourcent')+'px' });
				});
			}
			 
		}, 'json');
	}
	
	/**
	 * Gestion des utilisateurs !
	 * (affichage / ajout / suppression)
	 */
	this.teamInter = function()
	{		
		$.post('/fr/game/pages/intervention/generateur.ajax.php', { action : 'loadTeam' }, function( data ){
			
			 $('#content_edit_inter').html( '<h2>Gestion des membres de la team Inter</h2>' + data );
			 
		}, 'json');
	}
	
	this.validateTeam = function()
	{
		var pseudo 	= $('input[name=memberInter]').val();
		var droit	= $('select[name=droitsTeam] option:selected').val();
		
		$.post('/fr/game/pages/intervention/generateur.ajax.php', { action : 'validateTeam', u:pseudo, d:droit }, function( data ){
			
			message(data);
			$('#content_edit_inter').html( 'Que veux-tu faire ?' );
			 
		}, 'json');
	}
	
	this.deleteTeam = function( id )
	{
		$.post('/fr/game/pages/intervention/generateur.ajax.php', { action : 'deleteTeam', u:id }, function( data ){
			
			message(data);
			$('#content_edit_inter').html( 'Que veux-tu faire ?' );
			 
		}, 'json');
	}
	
	
	/**
	 * Modération des interventions !
	 * @param confirmation : confirmation d'une inter ou validation ?
	 */
	this.moderate = function( confirmation )
	{
		var titre = (confirmation == 1) ? 'Confirmation d\'un intervention !':'Validation d\'une intevention !';
	
		
		$.post('/fr/game/pages/intervention/generateur.ajax.php', { action : 'moderate', confirm:confirmation }, function( data ){
			
			$('#content_edit_inter').html( '<h2>'+ titre + '</h2>' + data );
			$('#viewLevel').html( objInter.getInterLevel( true ) );
			 
		}, 'json');
		
	}
	
	/**
	 * Modération des interventions !
	 */
	this.validateInter = function( valide )
	{
		var type 		= parseInt($('select[name=typeInter] option:selected').val());
		var stype		= parseInt($('select[name=typeInterPrecision] option:selected').val());
		var scenario	= $('textarea[name=scenario]').val();
		var scenariotech	= $('textarea[name=scenariotech]').val();
		var reussite	= $('input[name=scenario_ok]').val();
		var i			= $('input[name=idInterModerate]').val();
		var edition		= $('input[name=editInter]').val();
		var confirmation= parseInt($('input[name=confirmation]').val());
		var	phrase		= '';
		var msg_err		= '';
		
		if( valide == true )
		{
			if( confirmation == 1)
				phrase = 'Souhaites-tu vraiment valider cette intervention et la rendre disponible pour les joueurs ?';
			else
				phrase = 'Confirmes-tu cette intervention ?<br/><em>une confirmation sera faites par un autre membre</em>';
		}
		else
			phrase = 'Souhaites-tu vraiment refuser cette intervention ?';
			
		jConfirm( phrase, 'Confirmation', function(e){
			
			if( e == true)
			{
				// Récupération des véhicules
				var mesVehicules = 0;
				$('#addInterVehicule > div').not('.addInter').each(function(){
					if( mesVehicules == 0 )
						mesVehicules = $(this).attr('id');
					else
						mesVehicules += ',' + $(this).attr('id');
				});
				
				// Récupération du matériel
				var monMat = 0;
				$('#addInterMateriel > div').not('.addInter').each(function(){
					if( monMat == 0 )
						monMat = $(this).attr('id');
					else
						monMat += ',' + $(this).attr('id');
				});
				
				// Motif Refus :
				var refus = $('input[name=refus]').val();
				
				/* Mise à jour ! */
				$.post('/fr/game/pages/intervention/generateur.ajax.php', { 	action : 'validateInter', 
																	confirm:confirmation,
																	r:valide,
																	t:type,
																	s:stype,
																	sc:escape(scenario),
																	tech:escape(scenariotech),
																	re:escape(reussite),
																	i:i,
																	edit:edition,
																	veh:	mesVehicules,
																	mat:	monMat,
																	ren:	($('input[name=selectRenfort]:checked').length==1 ? true:false),
																	ref:escape(refus) }, function( data ){
					
					message(data[0]);
					$('#content_edit_inter').html( 'Que veux-tu faire ?' );
					$('#nombreInterRestante').html( data[2] );
					$('#nombreInterRestanteConfirm').html( data[3] );
					$('#nombreInterExistante').html( data[1] );
					$('#statsInter').html( data[4] );
					
				}, 'json');
			}	
		});		
	}
	
	
	/**
	 * Affichage des interventions disponible !
	 */
	this.viewInter = function( page, type, value ){
		
		var filtre 	= null;
		var val		= null;
		if( typeof(type) != 'undefined' && type != null )
		{
			filtre 	= type;
			val		= value;
		}
		
		// Gestion du titre
		var titre = ($('#TB_title').length == 0) ? '<h2>Editer une intervention !</h2>':'' ;
		
		
		$.post('/fr/game/pages/intervention/generateur.ajax.php', { action : 'viewInter', type:filtre, p:page, val:val }, function( data ){
			
			if( parseInt(data[0]) == 1 )
				$('#content_edit_inter').html( titre + data[1] );
			else
				$('.viewListInter').html( data[1] );
			 
		}, 'json');
		
	}
	
	
	/**
	 * Editer des interventions !
	 */
	this.editInter = function(id)
	{
		// Afffichage d'une intervention !
		if (is_numeric(id)) {
			$.post('/fr/game/pages/intervention/generateur.ajax.php', { action : 'moderate', id:id, confirm:1 }, function( data ){
				
				$('#content_edit_inter').html( data );
				$('#viewLevel').html( objInter.getInterLevel( true ) );
				 
			}, 'json');
		}
		// Affichage de la liste d'intervention d'un auteur !
		else{
			this.viewInter( 1, 'auteur', id );
		}
	}
	
	
	/**
	 * Rechercher une intervention !
	 */
	this.searchInter = function(){
		
		var id = $('input[name=interSearchId]').val();
		
		$.post('/fr/game/pages/intervention/generateur.ajax.php', { action : 'search', id:id }, function( data ){
			
			if( data[0] == true )
				objInter.editInter( id );
			else
				message(data[1]);
			 
		}, 'json');
		
	}
	
	/**
	 * Popup pour Rechercher par auteur
	 */
	this.searchPop = function(){
		
		var auteur = $('input[name=searchAuteur]').val();
	
		if ( $('input[name=searchAuteur]').length <= 0 ) {
			html = '<p>Rechercher toutes les interventions de : <input type="text" name="searchAuteur" size="35" style="color:grey;" value="#auteur"/> <a href="#/intervention/moderation" class="bouton" onclick="objInter.searchPop();" ><b>OK</b></a></p>'
				+ '<div id="detailsSearchAuteur"></div>';
			
			// Création popup
			$('#content_edit_inter').html( '<h2>Rechercher</h2>' + html);
		}
		else{
			
			$.post('/fr/game/pages/intervention/generateur.ajax.php', { action : 'searchAuteur', val:auteur }, function( data ){
				
				if( data[0]!=null )
					$('#detailsSearchAuteur').html( data[0] );
					
				message( data[1] );
				
			}, 'json');
			
		}
	}
	
	
	this.viewCatInter = function( id )
	{
		this.viewInter( 1, 'type', id );
	}
	
	
	
	/**
	 * Suppression de TOUTES les interventions d'un joueur (intervention non validée)
	 */
	this.deleteInter = function( auteur ){
		
		var a = auteur;
		jConfirm( 'Souhaitez-vous vraiment supprimer toutes les interventions (non validées) de "' + auteur + '" ?', 'Avertissement', function(e){
			
			if( e == true )
			{
					$.post('/fr/game/pages/intervention/generateur.ajax.php', { action : 'deleteInter', val:a }, function( data ){
						
						message( data );
						$('#content_edit_inter').html( 'Que veux-tu faire ?' );
						
					}, 'json');
			}
		});
	}

	
	function formatPx( e ){
		var a = e;
		a = e.substr( 0, e.indexOf('px'));
		return parseInt(a);
	}

	// Par défault, l'onglet "Choisir une scène existante" est activée
	this.start();
	
	
	/**
	 * Intéraction avec les différents éléments de la scène
	 */
	$(document).ready(function(){
		
		// Sélection d'un objet sur le générateur de scène
		$('.elementInter').die('mousedown').live('mousedown', function(){
			$('#genInter-itemSelect > span').html( $(this).children().attr('alt') );
			objInter.eActive = $(this).attr('id');
		});
		
		// Identification de l'élément choisi
		$('#genInter-itemSelect > span').die('mousover mouseout').live('mouseover mouseout', function(e){
			
			if( e.type == 'mouseover')
				$('#' + objInter.eActive ).addClass('localize');
			else
				$('#' + objInter.eActive ).removeClass('localize');		
			
		});
		
		// Clic sur le fond ou sur un autre onglet que paysage = on quitte !
		$('#genPop, #genInterScene-menu > span').die('click').live('click', function(){
			
			if (objInter.background !== null)
				objInter.closeItem();
			else
				jAlert('Tu dois choisir un décor pour ta scène d\'intervention !!!');
		});
		
		
		// Ajout d'un véhicule/matériel dans la liste de l'intervention
		$('#listeInterElement > div').die('click').live('click', function(e){
			
			var nombreVerif = 0;
			var typeVerif	= '';
			var levelVerif	= 0;
			var txtType = '';
			switch( objInter.typeActif )
			{
				case 'vehicule' : 
					nombreVerif = objInter.maxVehicule;
					typeVerif	= 'addInterVehicule';
					levelVerif	= parseInt($(this).attr('level'));
					txtType = 'Véhicule';
					break;
				case 'materiel' : 
					nombreVerif = objInter.maxMateriel;
					typeVerif	= 'addInterMateriel';
					txtType = 'Matériel';
					break; 
			}
			
			$('#' + typeVerif + ' .addInter').before( $(this).clone() );
				
			//gestion affichage du bouton +
			var n = parseInt($('#' + typeVerif + ' > div').length) - 1;
			if( n >= nombreVerif )
			{
				$('#' + typeVerif + ' > div.addInter').hide();
				fermerPopupAjax();
			}
			else{
				messageTxt( txtType + ' ajouté avec succès ! (encore ' + (nombreVerif - n) + ' possible)', 'ok' ,'#TB_ajaxContent');
			}
			
			// Raffraichissement du niveau actuel de l'intervention
			objInter.getInterLevel( false );
		});
		
		// Suppression d'un véhivule/matériel de la liste d'intervention !
		$('#addInterVehicule > div, #addInterMateriel > div').die('click').live('click', function(){
			if( !$(this).hasClass('addInter') )
			{
				$(this).fadeOut(function(){
					$(this).remove();
					
					var n = parseInt($('#addInterMateriel > div').length) - 1;
					if( n < objInter.maxMateriel )
						$('#addInterMateriel > div.addInter').show();
					
					var n = parseInt($('#addInterVehicule > div').length) - 1;
					if( n < objInter.maxVehicule )
						$('#addInterVehicule > div.addInter').show();
					
					// Raffraichissement du niveau actuel de l'intervention
					objInter.getInterLevel( false );
				});
			}
		});
		
		// Sélection d'un image de scène existante !
		$('#scene-listeImage > div ').die('click').live('click', function(){
			
			var img 	= $(this).children('img').attr('src');
			img 		= img.split('/');
			objInter.id = img[ (img.length - 1) ].replace('.jpg', '');
			$(this).parent().children('div').removeClass('active');
			$(this).addClass('active');
		});
		
		
		//Pagination des images de scène existante !
		$('#paginationGenInter > span').die('clik').live('click', function(data){
			objInter.loadPageImage( parseInt($(this).html()) );
			
			$('#paginationGenInter > span.active').removeClass('active');
			$(this).addClass('active');
			
		});
		
	});
}
