/* Fonctions utiles sur secteur 18 */

/**
 * Appel plus simple des popup Ajax ThickBox
 * @param {Object} titre
 * @param {Object} lien
 * @param {Object} rel
 */
function popup(titre)					{ tb_show( titre, null, false); }
function popupAjax(titre, lien, rel) 	{ tb_show(titre,lien,rel); }
function fermerPopupAjax() 				{ tb_remove(); }
function contenuPopupAjax(html) 		{ $('* #TB_ajaxContent').html( html ); }


function is_numeric (mixed_var) 
{
    return (typeof(mixed_var) === 'number' || typeof(mixed_var) === 'string') && mixed_var !== '' && !isNaN(mixed_var);
}

/**
 * Fonction d'animation de barre
 * @param {Object} c 	: nom de la classe des barres à animer
 * @param	max 		: largeur maximum (100%) en pixel
 */
function startBar( c, max )
{
	var maxWidth = max;
	$('.'+c).each( function(){
		
		var s = Math.round(parseInt($(this).attr('rel')) * maxWidth / 100);
		
		$(this).animate({ width: s+'px' });
	});
}


/**
 * FONCTION : affecte le bon style de bouton en fonction de la largeur du texte qu'il contient
 */
function classButton( type,  bouton )
{
	var classe = 'button-';
	if( type == 'button' ) 	var etiquette = $(bouton).html();
	else					var etiquette = $(bouton).val();
	
	if( etiquette.length > 35 ) 	classe += 'xxlarge';
	else if(etiquette.length > 30)	classe += 'xlarge';
	else if(etiquette.length > 20)	classe += 'large';
	else if(etiquette.length > 10)	classe += 'medium';
	else if(etiquette.length > 2)	classe += 'small';
	else 							classe += 'xsmall';
	
	$(bouton).addClass( classe );
}

function profil(e,userId)
{
	if(!e) e=window.event;
	var winProfil = $('#profil-joueur');
	var scrolltop = document.documentElement.scrollTop  || document.body.scrollTop;
	$('#profilView').html('<img src="/fr/static/template/chargement.gif" alt="chargement" style="margin:20px;" />');
	winProfil.css('top', (scrolltop+e.clientY+20)+'px');
	winProfil.css('left', (e.clientX)+'px');
	winProfil.show('fast');
	$('#profilView').load("/fr/user/infobulle.php?joueur="+userId);
}

function closeAll(e)
{
	if(!e) e=window.event;
	var obj = (e.target) ? e.target : e.srcElement;
	if(obj.tagName!='A')
		$('#profil-joueur').hide('fast');
	
	//on cache toute les tootltip
	$('* .qtip').hide();
}



/**
 * FONCTION : insertion de text dans un textarea
 * @param {Object} Text		: texte à ajouter
 * @param {Object} id_input	: id du textarea
 */
function insertText(Text, id_input )
{
	var obj = document.getElementById( id_input );
	obj.focus();
	
	if (document.selection && document.selection.createRange)  // Internet Explorer
	{
		sel = document.selection.createRange();
		if (sel.parentElement() == obj) 
			sel.text = Text;
	}
	
	else if (typeof(obj) != "undefined")  // Firefox
	{
		var longueur = parseInt(obj.value.length);
		var selStart = obj.selectionStart;
		var selEnd = obj.selectionEnd;
		obj.value = obj.value.substring(0,selStart) + Text + obj.value.substring(selEnd,longueur);
	}
	
	else 
		obj.value += Text;
	
	obj.focus();
}

/**
 * FONCTION : insertion d'un tag dans un textarea
 * @param {Object} Tag		: balise ouvrante
 * @param {Object} fTag		: balise fermante
 * @param {Object} id_input	: id du textarea
 */
function insertTags(Tag,fTag, id_input )
{
	var obj = document.getElementById( id_input );
	obj.focus();
	
	if (document.selection && document.selection.createRange)  // Internet Explorer
	{
		sel = document.selection.createRange();
		if (sel.parentElement() == obj) 
			sel.text = Tag + sel.text + fTag;
	}
	
	else if (typeof(obj) != "undefined")  // Firefox
	{
		var longueur = parseInt(obj.value.length);
		var selStart = obj.selectionStart;
		var selEnd = obj.selectionEnd;
		
		obj.value = obj.value.substring(0,selStart) + ' ' + Tag + obj.value.substring(selStart,selEnd) + fTag + ' ' + obj.value.substring(selEnd,longueur);
	}
	
	else
		obj.value += Tag + fTag;
	
	obj.focus();
}


/**
 * AFFICHAGE d'un message de validation
 * @param {Object} r
 */
function message(r, idContainer ) {
	
	
	if( typeof(idContainer) == 'undefined' )
	{
		idContainer = '#content';
	}
	// on à un paramètre ?
	if (r) {
		
		//--- MESSAGE
		if (r.message) {
			var e = $( idContainer +' .message');
			var html = '';
			var time = 3000;
			
			// pas encore créé ? on l'ajoute
			if ($(idContainer +' > .message:first').length == 0) 
				e = $('<p class="message"></p>').prependTo($(idContainer));
			else 
				e.show();
			
			//nombre de message affiché déjà
			var nMessage = $(idContainer +' > .message:first > div').length;
			
			//on boucle sur les messages
			for (var m in r.message) {
				html += '<div class="' + r.message[m][0] + '">' + r.message[m][1] + '</div>';
				time += 3000;
				nMessage++;
			}
			
			//on rajoute les messages dans le div
			if ($(idContainer +' > .message:first > div').length == 0) 
				e.html(html);
			else 
				e.prepend(html);
			
			
			setTimeout(function(){
				e.fadeOut('fast').html('');
			}, time);
		}
		
		//--- MENU
		// as-t-on un menu à mettre à jour ?
		if (r.menu) {
			for (var o in r.menu) 
			{
				$('#' + o).html('' + r.menu[o]).parent().fadeOut('slow', function(){
					$(this).fadeIn('normal', function(){
						$(this).fadeOut('slow', function(){
							$(this).fadeIn('normal');
						});
					});
				});
			}
		}
	}
}

/**
 * Envoi d'un message directement depuis javascript !
 */
function messageTxt( msg, classe, container )
{
	message( { "message":[[classe,msg]] }, container );
}

/**
 * FONCTION : traitement des données d'un formulaire en ajax !
 * 
 * > exigence de la balise <form> :
 * 		- class="ajaxForm" pour activer le traitement auto
 * 		- action="lien vers le fichier de traitement ajax.php" (ex: action="/fr/game/pages/caserne/ajax.php")
 * > exigence du formulaire :
 * 		- un champ <input type="hidden" name="reloadPage" value="/fr/game/pages/caserne/maPage.php">
 * 		- un champ <input type="button" name="submit"> qui permettra de poster
 * [optionnel]
 * 		- attribut "alt" au champ "reloadPage" pour rajouter des paramètres GET
 * 		- un champ <input type="hidden" name="ajaxFormConfirm" value="question de confirmation"> pour demander confirmation d'un submit
 */
function ajaxForm(nameOfForm)
{	
	var reloadPage	= $('form[name='+ nameOfForm +'] > input[name=reloadPage]').val();
	var optionnalGet= $('form[name='+ nameOfForm +'] > input[name=reloadPage]').attr('alt');
	var postPage	= $('form[name='+ nameOfForm +']').attr('action');
	var variables	= $('form[name='+nameOfForm+']').serializeArray();
	
	//on change le hash
	var newHash = reloadPage.replace('/fr/game/pages/','').split('.php');
	newHash = '#/'+newHash[0];
	window.location = newHash;
	
	$('#loading').show();
	
	$.post(postPage, variables , function(data){
		//on charge le résultat
		$('#content').load(reloadPage+'?result='+data+ (typeof(optionnalGet)!='undefined' ? '&'+optionnalGet:''), function(){
			reloadEcouteur();
		});
		
		setTimeout(function(){
			$('#loading').hide()
		}, 500);
	}, 'json');
}


/**
 * Fonction Timer
 * > affiche le temps restant jusqu'au timestamp souhaité !
 * 
 * @param "reste" : nombre de seconde restante avant la fin de l'évènement
 * @param "idTimer" : identifiant du span/div/... qui affiche le temps actuel
 */
function getTime(reste,idTimer) 
{
	if(document.getElementById(idTimer) != null)
	{
		var secondes = 0;
		var minutes = 0;
		var heures = 0;
		var jours = 0;
	
		var secondes_txt = "";
		var minutes_txt = "";
		var heures_txt = "";
		var jours_txt = "";
		
		var reste_avant;
		reste_avant = reste;
					
		while(reste >= 86400)	{ reste 	= reste-86400; 	jours++;	}
		while(reste >= 3600)	{ reste 	= reste-3600; 	heures++;	}
		while(reste >= 60)		{ reste 	= reste-60; 	minutes++;	}
		secondes = reste;
		
		secondes_txt= " "+secondes+" s";
		minutes_txt	= " "+minutes+" min";
		heures_txt	= " "+heures+" h";	
		jours_txt	= " "+jours+" j";	
		
		if(jours >= 1)
			$('#'+idTimer).html(jours_txt+" "+heures_txt+" "+minutes_txt);
					
		if(heures >= 1 && jours <= 0)
			$('#'+idTimer).html(heures_txt+" "+minutes_txt+" "+secondes_txt);
		
		if(secondes >= 1 && minutes >= 1 && heures <=0 && jours <= 0) 
			$('#'+idTimer).html(minutes_txt+" "+secondes_txt);
		
		if(secondes == 0 && minutes >= 1 && heures <=0 && jours <= 0)
			$('#'+idTimer).html(minutes_txt);
		
		if(secondes < 60 && minutes < 1 && heures < 1 && jours < 1)
			$('#'+idTimer).html(secondes_txt);
		
		
		//Fin du timer
		if(secondes < 1 && minutes < 1 && heures < 1 && jours < 1) 
		{
			//récursivité (relance du timer)
			if(idTimer == 'timerCompetition')
			{
				getTime( 3600, "timerCompetition" );
			}
			else if( idTimer == 'timerDepart' || idTimer == 'timerDepartMenu' )
				$('#'+idTimer).parent().html('Départ écoulé !');
			else
				$('#'+idTimer).parent().parent().html('Terminé !');
		}
		//Le timer se poursuit
		else{
			reste = reste_avant - 1;
			window.setTimeout("getTime("+reste+",\""+idTimer+"\");", 1000); 
		}
		
	}
	return false;
}

/**
 * FONCTION : chronomètre
 * @param {Object} idChrono
 */
function Chronometre( o )
{
	this.sec 		= 0;	// seconde écoulée
	this.end 		= null;	// seconde du temps final
	this.interval	= null;
	
	for( var i in o){
		this[i] = o[i];
	}
	
	/* Démarrer le Chronomètre ! */
	this.start = function( idChrono ){
		a = this;
		
		// affichage du texte !
		if( idChrono != undefined )
			$('#' + idChrono ).html( this.text() );
		
		if( this.end!=null && this.end<= this.sec )
			this.stop();
		else
			this.sec++;
		
		if( this.interval == null )
		{
			this.sec		= 0;
			this.interval 	= setInterval('a.start("'+idChrono+'")', 1000);
		}
	}
	
	/* Arrêter le Chronomètre ! */
	this.stop = function(){
		clearInterval( this.interval );
		this.interval = null;
		console.log('Fini !');
	}
	
	/* Conversion des secondes en textes */
	this.text = function(){
		var texte			= '';
		var jours 			= Math.floor( this.sec/86400 );
		var heures 			= Math.floor( (this.sec - (86400*jours))/3600 );
		var minutes 		= Math.floor( (this.sec - (86400*jours) - (3600*heures)) / 60);
		var secondes 		= this.sec - (86400*jours) - (3600*heures) - (60*minutes);
		var secondes_txt 	= secondes	+ 'sec';
		var minutes_txt 	= minutes 	+ 'min';
		var heures_txt 		= heures 	+ 'h';
		var jours_txt 		= jours 	+ 'j';
		
		if(jours >= 1)
			texte = jours_txt+" "+heures_txt+" "+minutes_txt;		
		if(heures >= 1 && jours <= 0)
			texte = heures_txt+" "+minutes_txt+" "+secondes_txt;
		if(secondes >= 1 && minutes >= 1 && heures <=0 && jours <= 0) 
			texte = minutes_txt+" "+secondes_txt;
		if(secondes == 0 && minutes >= 1 && heures <=0 && jours <= 0)
			texte = minutes_txt;
		if(secondes < 60 && minutes < 1 && heures < 1 && jours < 1)
			texte = secondes_txt;
		
		return texte;
	}
}


/**
 * FONCTION : retourne si OUi (true) ou non (false) une valeur est contenue dans un array
 * @param {Object} valeur
 * @param {Object} array
 */
function in_array(valeur, array) 
{
    for(var i = 0, l = array.length; i < l; i++) {
        if(array[i] == valeur) {
            rowid = i;
            return true;
        }
    }
    return false;
}

function trim ( texte )
{
	return texte.replace(/^\s+/g,'').replace(/\s+$/g,'')
} 


function number_format( number, decimals, dec_point, thousands_sep ) {	
	var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 0 : decimals;
	var d = dec_point == undefined ? "," : dec_point;
	var t = thousands_sep == undefined ? " " : thousands_sep, s = n < 0 ? "-" : "";
	var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
	
	return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}

//---- FACEBOOK function
//---- Affiche/Cache le module pour délier son compte secteur18 et facebook
function delierCompte(e, type) {
	e.preventDefault();
	if(type == 'valider') { 
		
		$.post('/fr/game/pages/administration/monCompte.ajax.php', 
			{ 	action:'disassociate_facebook', 
				email:$('input[name=facebook_email]').val(),
				pass:$('input[name=facebook_pass]').val()
				}, function( data ){
			
			if(data=='ok'){
				jAlert('<div class="ok">Votre compte Facebook a été délier de secteur18 avec succès !</div>', 'Délier son compte Facebook de secteur 18');
				pageLoad('/fr/game/#/administration/monCompte');
			}
			else if( data == 'email')
				jAlert('Adresse Email déjà prise ou incorrecte !', 'Délier son compte Facebook de Secteur 18');
			else if( data == 'pass')
				jAlert('Mot de passe incorrecte !', 'Délier son compte Facebook de Secteur 18');
			
		});
	
		
	} else { 
		$('#facebookDelier').fadeIn('fast',function(){
			$('#facebookConfig').fadeOut('fast');
		}); 
	}
}


//---- Lie le compte cromimi et facebook
function associerCompte() {
	$('#fbCompteSynchro').append('<img style="position:absolute;" id="loading" src="/static/images/loading.gif" />');
	// demande la connexion à son profil facebook
	FB.Connect.requireSession(function() {		
		FB.Connect.showPermissionDialog('publish_stream,offline_access', function(perms){
			$.ajax({
				type: "POST",
				url: "/fr/game/pages/administration/monCompte.ajax.php",
				data: {'action':'associate_facebook'},
				success: function(data){
					if(data=='ok') {
						jAlert('<div class="ok">Votre compte Facebook a été associer à secteur18 avec succès !</div>', 'Associer son compte Facebook à Secteur 18');
						pageLoad('/fr/game/#/administration/monCompte');
					
					} else if(data=='nok') {
						jAlert('Comptes déjà synchronisés', 'Associer son compte Facebook à Secteur 18');	
						$('#loading').remove();					
				 	
					} else {
						jAlert('Une erreur est survenue. Réessayes plus tard', 'Associer son compte Facebook à Secteur 18');
						$('#loading').remove();
					}
					
					
				}
			});
		});	
	});
}

function is_array(variable)
{
	var source = variable.toSource();
	return (source.search(/^\[([^,]*,)+[^,]*\]/) != -1);
}


function compareArray(a1, a2)
{
	if(a1.length != a2.length) {
		return false;
	}
	else 
	{
		for(var a=0; a<a1.length; ++a) 
		{
			if(a1[a] != a2[a])
			{
				return false;
			}
		}
	}
	return true;
}


function getWindowHeight() {
	var windowHeight=0;
	if (typeof(window.innerHeight)=='number') {
		windowHeight=window.innerHeight;
	} else {
		if (document.documentElement&& document.documentElement.clientHeight) {
			windowHeight = document.documentElement.clientHeight;
		} else {
			if (document.body&&document.body.clientHeight) {
				windowHeight=document.body.clientHeight;
			}
		}
	}
	return windowHeight;
}


function getWindowWidth() {
 var windowWidth=0;
 if (typeof(window.innerWidth)=='number') {
  windowWidth=window.innerWidth;
	} else {
  if (document.documentElement&& document.documentElement.clientWidth) {
   windowWidth = document.documentElement.clientWidth;
		} else {
   if (document.body&&document.body.clientWidth) {
    windowWidth=document.body.clientWidth;
			}
		}
	}
	return windowWidth;
}


function thisMovie(movieName) {
	var ie = navigator.appName.indexOf("Microsoft") != -1;
	if (ie)
		return window[movieName];
	else
		return document[movieName];

	return flashroot;
}

/**
 * Communication Javascript -> Flash pour activer/désactiver le son
 * @param {Object} id : id du flash
 * @param {Object} state : état (1 ou 0)
 * @param {object} save : doit-on sauvegarder la mise à jour ?
 */
function changeSoundFlash( id , state, save )
{
	try{

		thisMovie( id ).setVolume( state );
		if( state == 0)
		{
			$('* .soundOn').hide();
			$('* .soundOff').show();
		}
		else{
			$('* .soundOff').hide();
			$('* .soundOn').show();
		}
		
		if( save == 1 )
			updateSound( state ); // Mise à jour dans la bdd
	}
	catch(e){}
	
}

/**
 * Mise à jour de la config du son pour le joueur
 */
function updateSound( state ){
	$.post('/fr/game/pages/administration/monCompte.ajax.php', { action:'updateSound', volume:state });
}

/**
 * Jouer un son flash
 * => flash concerné "id_flash", nom du son "id_sound"
 * => le jouer "n" fois, tous les "intervalle" millisecondes
 */
function playSoundFlash( id_flash, id_sound, n, intervalle )
{
	try{
		if( n == undefined )
			n = 1;
			
		if( intervalle == undefined )
			intervalle = 0;
		
		thisMovie(id_flash).playSound( id_sound, n, intervalle );
	}
	catch(e){}
}

/**
 * Stoper un son flash
 */
function stopSoundFlash( id_flash, id_sound )
{
	try{
		if( id_sound == undefined )
			id_sound = null;
		
		if(typeof(thisMovie(id_flash).stopSound) != "undefined"){
			thisMovie(id_flash).stopSound( id_sound );
		}
		else
		{
			setTimeout( "stopSoundFlash('secteur18_sound',null)", 500);
		}
	}
	catch(e){}
}





/**
 * Fonction Caroussel : gère un petit caroussel de manière très simple
 * @param {Object} id		id du caroussel
 * @param {Object} width	largeur d'une vignette
 * @param {Object} nb		nombre de vignette à afficher en même temps
 * @to	06/01/2011	Renan	Modification pour gérer début et fin de course	
 * @to	14/01/2011	Renan	Amélioration > gestion automatique largeur caroussel + centrage auto des vignettes
 * @to	25/08/2011	Renan	Amélioration > gestion automatique largeur des vignettes (avec padding, margin et border)
 */
function Carrousel(id, width, height, nb){
	
	// On défini la largeur et la hauteur de chaque vignette !
	$('#'+id+' .item').css('width', width + 'px').css('height', height + 'px');								
	
	// Nombre de vignette + largeur totale en tenant compte des propriétés border/padding/margin
	var total 		= $('#' + id + ' .item').length; 
	var widthTotal	= $('#' + id + ' .item').outerWidth(true);
	var heightTotal	= $('#' + id + ' .item').outerHeight(true);
	
	$('#'+id).css('height', heightTotal + 'px');
	
	// Centrage des vignettes
	if( total < nb )
		nb = total;
	
	// Largeur/Hauteur du Container des vignettes, puis du Carrousel complet
	$('#'+id+' .interieur-carrousel').css('width', parseInt( (nb * widthTotal) )+'px').css('height', parseInt( heightTotal )+'px');
	$('#'+id ).css('width', parseInt( (nb * widthTotal) + 100)+'px').css('height', parseInt( heightTotal )+'px');					
	
	// Vignette affichée actuellement !
	$('#' + id).append('<span id="span' + id + '" style="display:none;">1</span>');
	
	// Mise à jour des flèches de navigation
	refreshLinkCaroussel( 1 ); 
	
	//--- NAVIGATION : suivante
	$('#' + id + ' a.next').die('click').live('click', function(){
		var total;
		var current;
		var left;
		var leftActuel; //permet de gérer la limite
		
		current 	= parseInt($('#span' + id).html());
		left 		= parseInt($('#' + id + ' .items').css('left'));
		total 		= $('#' + id + ' .item').length;	//nombre d'élément au total
		
		if( current < total )
		{
			$('#' + id + ' .items').animate({
			left: '-=' + (widthTotal * nb)
			}, 'slow');
			current = current + nb;
			refreshLinkCaroussel( current );
			$('#span' + id).html(current);
		}
		
		return false;
	});
	
	//--- NAVIGATION : suivante
	$('#' + id + ' a.prev').die('click').live('click', function(){
		var current;
		var left;
		
		current 	= parseInt($('#span' + id).html());
		left 		= parseInt($('#' + id + ' .items').css('left'));
		
		if (current > 1) {
			$('#' + id + ' .items').animate({
				left: '+=' + (widthTotal * nb)
			}, 'slow');
			
			current = current - nb;
			refreshLinkCaroussel( current );
			$('#span' + id).html(current);
		}
		
		return false;
	});
	
	
	//--- FONCTION : Mise à jour des flèches de navigation (visible/cachée)
	function refreshLinkCaroussel( current )
	{		
		var total;
		total = $('#' + id + ' .item').length;	//nombre d'élément au total
		
		if( current == total || ((current + (nb-1)) >= total) )
			$('#' + id + ' a.next img').hide();
		else
			$('#' + id + ' a.next img').show();
		
		if( current == 1 )
			$('#' + id + ' a.prev img').hide();
		else
			$('#' + id + ' a.prev img').show();
	}
}
