/**
 * @brief	Fonctions utilisées pour le sport et les compétitions
 * @author	Renan
 * @since	28/05/2010
 * @to		02/02/2011	- Renan	- Mise à jour répertoires
 * @to		03/02/2011	- Renan	- Ajout des Olympiades
 * @version	1
 */

function Sport()
{
	this.id = 0; //id de l'excercice
	
	this.info = function()
	{
		$.post('/fr/game/pages/sport/entrainement.ajax.php', { action:'detail', id:this.id}, function(data){
			
			$('#detailEntrainement > span').html(data[1]);
			$('input[name=excercice]').attr('value', data[0]);
			$('input[name=submit]').attr('disabled',false);
		}, 'json');
	}
};


function Competition()
{
	this.id 			= 0; 	//id du sport effectué
	this.participants	= 0;	//nombre de participants pour cette épreuve
	this.viewBulletin 	= false;
	
	/* sélectionner un sport */
	this.select = function()
	{
		this.viewBulletin 	= false;
		$('input[name=inscriptionCompet]').attr('disabled',true);
		
		$.post('/fr/game/pages/sport/competition.ajax.php', { action:'select', id:this.id}, function(data){

			$('#detailCompet-container').html(data[1]);
			
			startBar('sportBar', 150);
			
		}, 'json');
	}
	
	/* bulletin inscription */
	this.bulletin = function()
	{
		this.viewBulletin = true;
		
		popup('Participation à une compétition sportive');
	
		$.post('/fr/game/pages/sport/competition.ajax.php', { action:'bulletin', id:this.id}, function(data){
			
			contenuPopupAjax( data[1] );
			
		}, 'json');
		
	}
	
	
	/* Aperçu des joueurs choisis */
	this.generateTeam = function()
	{
		var genre 		= $('input[name=profilCompet-genre]:checked').val();
		var qualite 	= $('input[name=profilCompet-qualite]:checked').val();
		var grade 		= escape($('input[name=profilCompet-grade]:checked').val());
		var nParticipant= $('input[name=nbParticipants]').length > 0 ? parseInt($('input[name=nbParticipants]').val()):0;
	
		if( isNaN(nParticipant) )
			jAlert('Le nombre de participants est incorrecte !');
		else
		{
			this.participants = nParticipant;
			$.post('/fr/game/pages/sport/competition.ajax.php', { action:'generateTeam', genre:genre, qualite:qualite, grade:grade, id:this.id, n:nParticipant}, function(data){
		
				$('#previewEquipeSelect').html(data[1]);
				
			}, 'json');
		}
		
	}
	
	
	/* inscription */
	this.inscription = function()
	{
		var lesJoueurs 	= '';		
		var i 			= 0;
		$('#selectionPompierCompet > div').each( function() {
			
			if(i>0)
				lesJoueurs += ',';
			lesJoueurs += $(this).attr('id');;
			i++;
		});
		
		$.post('/fr/game/pages/sport/competition.ajax.php', { action:'inscription', id:this.id, joueurs:lesJoueurs, participants:this.participants}, function(data){
			
			competition.select();
			fermerPopupAjax();
			message(data[2]);
			
		}, 'json');
	}
	
	/* Affichade des derniers résultats des compétitions */
	this.resultats = function()
	{
		popup('Affichage des derniers résultats');
		$.post('/fr/game/pages/sport/competition.ajax.php', { action:'resultats', id:this.id }, function(data){
			
			contenuPopupAjax( data[1] );
			
		}, 'json');
	}
};



function Olympiade( prix ){
	
	this.id			= 0;	// identification de l'olympiade (reste à 0 lors de la création)
	this.day 		= 0;	// nombre de jour
	this.niveauMin	= 0;	// niveau minimum pour participer à ces olympiades
	this.listeSport	= new Array();
	this.sportChoisi= new Array();
	this.idPlanning = null;
	this.nEpreuve	= 0;	// nombre d'épreuve sélectionnée
	this.prix 		= prix;
	this.choixTxt	= 'Choisir une épreuve';
	
	//initialisation des sports disponibles
	$.post('/fr/game/pages/sport/olympiade.ajax.php', { action:'loadingSport' }, function( sport ){
		
		olympiade.listeSport = sport;
		for(k in sport){
			olympiade.sportChoisi[k] = false;
		}
		
	}, 'json');
	
	
	/* Initialisation du planning */
	this.initPlanning = function(){
		
		this.day 		= 0;
		this.nEpreuve	= 0;
		
		for(k in this.listeSport){
			olympiade.sportChoisi[k] = false;
		}
		
		this.unSelect();
	}
	
	/* Configuration de l'Olympaide */
	this.configurate = function(){
		
		this.initPlanning();
			
		$.post('/fr/game/pages/sport/olympiade.ajax.php', { action:'createPop' }, function( data ){
			
			contenuPopupAjax( data );
			olympiade.addDay(1);
			
		}, 'json');
		
	}
	
	
	/* Gestion du planning (ajout/suppression d'un jour) */
	this.addDay = function( n ){
		
		// Mise à jour du planning
		this.unSelect();
		
		if( n > 0 && this.day < 3)
		{
			this.day++;
			$('#nbJourOlympiade').html( this.day );
			
			$('#planningOl-container').append(	'<div class="planningOlDay" id="day'+this.day+'" style="display:none">'
												+'	<div class="planningOl legend">Jour '+this.day+'</div>'
												+' 	<div class="planningOl case" id="p'+this.day+'1">'+ this.choixTxt +'</div>'
												+' 	<div class="planningOl case" id="p'+this.day+'2">'+ this.choixTxt +'</div>'
												+'</div>');
			$('#day'+this.day).fadeIn('fast');
		}
		else if( n < 0 && this.day > 1){
			
			this.day--;
			
			$('#day'+(this.day+1)+' .case > div').each(function() {
				
				var id = $(this).attr('id');
				olympiade.etatSport( id.substr(1) , false);
				
			});
			
			$('#nbJourOlympiade').html( this.day );
			$('#day'+(this.day+1)).fadeOut('fast', function(){ $(this).remove(); });
		}
		
		$('#priceOl').html( this.prix * this.day );
		
	}
	
	/* Liste les sport disponibles */
	this.liste = function( id ){
		this.idPlanning = id;
		
		// Mise à jour du planning
		this.unSelect();
		
		var maListe = '<select name="selectSport" onchange="olympiade.setSport()"><option value="0">'+ this.choixTxt +'</option>';
		
		for(key in this.listeSport)
		{
			if( this.sportChoisi[key] == false  ){
				//maListe += '<option value="'+this.listeSport[key].id+'">'+this.listeSport[key].nom+'</option>';
				maListe += '<option value="'+ key +'">'+this.listeSport[key].nom+'</option>';
			}
		}
		
		maListe += '</select>';
		$('#'+id).html( maListe );
	}
	
	/* Sélection du sport pour un jour donné */
	this.setSport = function(){
		
		var val 	= this.listeSport[ $('select[name=selectSport] option:selected').val() ].id ;
		var texte	= '<img src="' + this.listeSport[ $('select[name=selectSport] option:selected').val() ].img + '" align="absmiddle" style="width:35px; height:35px;" class="infobulle" alt="'+$('select[name=selectSport] option:selected').html()+'"/>';

		
		$('#'+ this.idPlanning).html( '<div id="s'+ val +'">' + texte + '</div>'  );
		
		this.etatSport( val, true );
		this.idPlanning = null;
	}
	
	/* Mets à jour si un sport lorsqu'on ajoute/supprime une épreuve au planning */
	this.etatSport = function( id, setValue )
	{
		for(key in this.listeSport)
		{
			if( this.listeSport[key].id == id  ){
				this.sportChoisi[key] = setValue;
			}
		}
		
		//Compteur d'épreuve
		if( setValue )
			this.nEpreuve++;
		else
			this.nEpreuve--;
	}
	
	/* Supprime la liste déroulante si active */
	this.unSelect = function(){
		if($('select[name=selectSport]').length > 0){
			var idtemp = $('select[name=selectSport]').parent().attr('id');
			$('#'+idtemp).html( this.choixTxt );
		}
	}
	
	
	/* On créer l'olympiade comme on l'a configuré */
	this.start = function(){
		
		var erreur			= '';
		var nom 			= trim($('.formulaire input[name=name]').val());
		var niveauMin		= parseInt($('.formulaire select[name=niveauMin] option:selected').val());
		var epreuves		= null;
		
		
		// Contrôle du formulaire
		if( nom == '' )
			erreur += 'Nom invalide ou absent !<br/>';
			
		if( this.nEpreuve < (this.day*2) )
			erreur += 'Planning incomplet !';
		
		// Affichage des erreurs ou validation
		if( erreur != '' )
		{
			jAlert( 'Création de  l\'olympiade impossible, il existe des errreurs :<br/><br/>' + erreur, 'Erreur !' );
		}
		else{
			
			// Récupération des épreuves sportives choisie pour cette olympiade !
			$('#planningOl-container > div').each(function(){
				
				var id 		= $(this).attr('id');
				var sport	= '';
				$('#' + id + ' .case').each(function(){
					
					var idSport = $(this).children().attr('id');
					
					if( sport == '' )
						sport = idSport.substr(1);
					else
						sport+= '-'+idSport.substr(1);
				});
				
				if( epreuves == null )
					epreuves = sport;
				else
					epreuves += ','+sport;
			});
			
			// Enregistrement dans la base de données !
			$.post('/fr/game/pages/sport/olympiade.ajax.php', { action:'saveOlympiade', nom:escape(nom), niveauMin:niveauMin, planning:epreuves }, function( result ){
					fermerPopupAjax();
					message( result );
			});
		}
	}
	
	/**
	 * Démarer une inscription !
	 */
	this.register = function( type ){
		
		$.post('/fr/game/pages/sport/olympiade.ajax.php', { action:'validate', type:type, id:this.id }, function(data){
			 
			fermerPopupAjax();
			message( data[1] );
			
			if( data[0] == true )
			{
				window.location.reload();
			}
			
		}, 'json');
		
	}
};	
