// Contraction de la fonction de ciblage d'un objet par son ID
var drop    = 0;
var IE      = (document.all) ? true : false;

/*
* Blocage du clic droit de la souris
* @author Guichard Yann
**/
document.oncontextmenu = function(){ return false; }

function checknum()
{
var valeur = document.formulaire.champ.value;
var reg = new RegExp("[^0-9]", "gi");
if(valeur.match(reg))
{
document.getElementById("warn").innerHTML = "<span style='color: red;'>Attention ! Ce champ ne doit contenir que des chiffres !</span>";
}
else
{
document.getElementById("warn").innerHTML = "";
}
} 

function sonID(objID)
{
    return document.getElementById(objID);
}

function in_array (val, tab) 
{
	for(var i=0, l=tab.length ; i < l ; i++) 
    {
		if(tab[i] == val) return true;
	}
	return false;
}

function is_tag (string) 
{
	var liste_tags = ['a', 'p', 'div', 'span', 'img', 'table', 'tr', 'td'];
	return in_array(string, liste_tags);
}

function do_nothing () {}

function time () 
{
	return Math.floor((new Date()).getTime() / 1000);
}

function Temps ( tps ) 
{
	var s = tps;
	var m = Math.floor(s/60);
	s %= 60;
	var h = Math.floor(m/60);
	m %= 60;
	
	var ss = ( s < 10 ) ? "0"+s : s;    
	var mm = ( m < 10 ) ? "0"+m : m;
    
	return h+':'+mm+':'+ss;
}

function date ( tps ) 
{
	var d  = new Date();
	d.setTime(tps * 1000);

	var a  = d.getYear();
	if(a < 200) a += 1900;

	var mois   = new Array(  "janvier","fevrier","mars","avril","mai","juin", "juillet","aout",
                             "septembre","octobre","novembre","decembre"  );
	var mo     = mois[d.getMonth()];
	var h      = d.getHours();
	var m      = d.getMinutes();
	var hh     = ( h < 10 ) ? "0"+h : h;
	var mm     = ( m < 10 ) ? "0"+m : m;
	
	return d.getDate()+' '+mo+' '+a+' '+hh+':'+mm;
}

/* Made by Mathias Bynens <http://mathiasbynens.be/> */
function number_format(a, b, c, d) 
{
    a = Math.round(a * Math.pow(10, b)) / Math.pow(10, b);
    e = a + '';
    f = e.split('.');
    if (!f[0]) f[0] = '0';
    if (!f[1]) f[1] = '';
    
    if (f[1].length < b) 
    {
        g = f[1];
        for (i=f[1].length + 1; i <= b; i++) 
        {
            g += '0';
        }
        f[1] = g;
    }
    if(d != '' && f[0].length > 3) 
    {
        h = f[0];
        f[0] = '';
        
        for(j = 3; j < h.length; j+=3) 
        {
            i = h.slice(h.length - j, h.length - j + 3);
            f[0] = d + i +  f[0] + '';
        }
        j = h.substr(0, (h.length % 3 == 0) ? 3 : (h.length % 3));
        f[0] = j + f[0];
    }
    c = (b <= 0) ? '' : c;
    
    return f[0] + c + f[1];
}

function nombre ( nb ) 
{
	return number_format( nb, 0, ',', '.');
}

function txt2str ( txt ) 
{
	if( !txt ) return '';
	
	var bbcExp = [
		/\\\\([\\\\"'])/,					// stripslashes
		/(\r\n|\r|\n)/,						// nl2br
		/\[url\]http:\/\/(.*)\[\/url\]/,	// url
		/\[url:(.*)\](.*)\[\/url\]/,		// lien
		/\[img\](.*)\[\/img]/,				// img
		/\[color:(.*)\](.*)\[\/color\]/,	// couleur
		/\[c:(.*)\](.*)\[\/c\]/,			// c = couleur
		/\[u\](.*)\[\/u]/,					// u = souligne
		/\[s\](.*)\[\/s]/,					// s = barre
		/\[i\](.*)\[\/i]/,					// i = italique
		/\[b\](.*)\[\/b]/					// b = gras
	];
	var bbcRpl = [
		'$1',
		'<br/>',
		'<a href="$1">$1</a>',
		'<a href="$1">$2</a>',
		'<img src="$1" alt="image non trouvee"/>',
		'<span style="color:$1">$2</span>',
		'<span style="color:$1;">$2</span>',
		'<span style="text-decoration:underline;">$1</span>',
		'<span style="text-decoration:line-through;">$1</span>',
		'<span style="font-style:italic;">$1</span>',
		'<span style="font-weight:bold;">$1</span>'
	];
	
	for( i in bbcExp ) txt = txt.replace(bbcExp[i], bbcRpl[i]);
	
	return txt;
}

var dim_window = function () 
{
	return {
		scrollLeft    : function() { return IE ? document.documentElement.pageXOffset  : document.body.scrollLeft     },
		scrollTop     : function() { return IE ? document.documentElement.pageYOffset  : document.body.scrollTop      },
		width         : function() { return document.documentElement.clientWidth  },
		height        : function() { return document.documentElement.clientHeight }
	}
}();

var souris = function () {    
	return {
		x : dim_window.width() / 2,
		y : dim_window.height() / 2
	}
}();

document.onmousemove = function (ev) {
	ev = ev || window.event;
	if( IE )
    {
        souris.x = ev.clientX + dim_window.scrollLeft();
        souris.y = ev.clientY + dim_window.scrollTop();
    }
	else if(document.layers || document.getElementById)
    {
		souris.x = ev.pageX;
		souris.y = ev.pageY;
	}
	else if(windows.opera){
		souris.x = e.clientX;
		souris.y = e.clientY;
	}
}

uniqid = (function () {
	var id = 0; return function () { return id++; };
})();

/**  =========================  ASSESSEUR  =========================  **/

function $(id) 
{
	return document.getElementById(id);
}

function get_by_tag (tag, parent) 
{
    if( !parent ) parent = document.body;
	return parent.getElementsByTagName(tag);
}

function get_by_class (classname, parent) 
{
    if( !parent ) parent = document.body;
    var tab = [];
    var rexp = new RegExp('\\b' + classname + '\\b');
    var els = parent.getElementsByTagName("*");
	
    for(var i=0,j=els.length; i<j; i++)
        if(rexp.test(els[i].className))	tab.push(els[i]);
	
    return tab;
}

/**  =========================  MANIPULATION D'OBJET  =========================  **/

function create(elem, attributs, css) 
{
	var o = is_tag(elem) ? document.createElement(elem) : document.createTextNode(elem);
	
	o.accrocher = function (parent) {
		o.parent =  parent || document.body;
		o.parent.appendChild(o);
	}
	
	o.append = function (elem) {
		var object = ( typeof(elem) == 'string' ) ? create(elem) : elem;
		object.parent = o;
		o.appendChild(object);
	}
	
	o.set_opacity = function (x) {
		if(typeof o.style.MozOpacity != "undefined")	o.style.MozOpacity = x;
		if(typeof o.style.filter != 'undefined')
        {
			if (o.style.filter.indexOf("alpha") == -1) 
            {
				var existingFilters = "";
				if (o.style.filter) existingFilters = o.style.filter+" ";
				o.style.filter = existingFilters + "alpha(opacity="+ x * 100 +")";
			}
			else o.filters.alpha.opacity = x * 100;
		}
		if(typeof o.style.opacity != 'undefined')	o.style.opacity = x;
	}
	
	o.add_ev = function (ev, fonction) {
		if( IE ) o.attachEvent("on"+ev, fonction);
		else o.addEventListener(ev, fonction, true);
		// var node = IE ? event.srcElement : event.target;
	}

	o.del_ev = function (ev, fonction) {
		if( IE ) o.detachEvent("on"+ev, fonction);
		else o.removeEventListener(ev, fonction, true);
	}

	o.destroy = function () {
		o.parent.removeChild(o);
	}
	
	for( var i in css ) 
    {
		if(i == 'opacity')    o.set_opacity(css[i]);
		else                  o.style[i] = css[i];
	}
    
	for( var i in attributs )
    {
        o[i] = attributs[i];  
    }
    
	return o;
}


/** =========================  COOKIES  =========================  **/

function ecrire_cookie(nom, valeur, expiration, chemin, domaine, securise) 
{
	document.cookie = nom   + "=" + escape(valeur)
                            + ( expiration ? '; expires='+expiration.toGMTString() : '' )
                            + ( chemin ? '; path='+chemin : '' )
                            + ( domaine ? '; domain='+domaine : '' )
                            + ( securise ? '; secure' : '' );
}

function get_cookie_val(offset)
{
	var endstr = document.cookie.indexOf (";", offset);
	if (endstr == -1) endstr = document.cookie.length;
    
	return unescape(document.cookie.substring(offset, endstr));
}

function lire_cookie(nom)
{
	var arg = nom + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var i = 0;
    
	while (i < clen)
    {
		var j = i + alen;
		if (document.cookie.substring(i, j) == arg) return get_cookie_val(j);
		i = document.cookie.indexOf(" ", i) + 1;
		if (i == 0) break;
	}
    
	return null;
}

function cookie_exists(nom)
{
	var search = nom + "=";
	if (document.cookie.length > 0)
    {
		offset = document.cookie.indexOf(search);
		if (offset != -1) return true;
	}
    
	return false;
}


/**  =========================  AJAX  =========================  **/

function globaleval (script)
{
	if(window.execScript)  return window.execScript(script);
	else if(navigator.userAgent.indexOf('KHTML') != -1)
    { 
        //safari, konqueror..
		var s = document.createElement('script');
        
		s.type        = 'text/javascript';
		s.innerHTML   = script;
		document.getElementsByTagName('head')[0].appendChild(s);
		return true;
	}
	else   return window.eval(script);
		
}

function getXHR() 
{
	var xhr = null;

	if(window.XMLHttpRequest || window.ActiveXObject) 
    {
		if(window.ActiveXObject) 
        {
			try 
            {
				xhr = new ActiveXObject("Msxml2.XMLHTTP");
			} 
            catch(e) 
            {
				xhr = new ActiveXObject("Microsoft.XMLHTTP");
			}
		}
		else 
        {
			xhr = new XMLHttpRequest();
		}
	}
	else 
    {
		alert("Votre navigateur ne supporte pas l'objet XMLHTTPRequest...");
		return null;
	}
	return xhr;
}

function ajax(url, methode, donnees, action, asynchrone)
{	
	var xhr = getXHR();
	if(xhr && xhr.readyState != 0) 	xhr.abort(); 

	xhr.onreadystatechange = function(){
                                    		if( typeof(action) == "function" )
                                            { 	
                                                /* si on ne met qu'une fonction en réponse */
                                    			if(xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) action(xhr);
                                    		}
                                    		else
                                            {  	
                                                // si on passe un tableau de fonctions   
                                                // [  0 : non initialisé                 
                                                //    1 : ouverture du transfert         
                                                //    2 : données envoyées               
                                                //    3 : les données arrivent           
                                                //    4 : données arrivées         ]     
                                    			var fonct = action[xhr.readyState];
                                    			if(typeof(fonct) == "function" ) fonct(xhr);
                                    		}
	                                                                                                               }

	switch(methode)
    {
		case "GET" :
			xhr.open(methode, url+'?'+donnees, asynchrone);
			xhr.send(null);
			break;
		case "POST" :
			xhr.open(methode, url, asynchrone);
			xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');			
			xhr.send(donnees);
			break;
		default :
			alert("Mauvaise méthode de l'xhr...");
			xhr.abort();
	}
}

/**  =========================  DIVERS  =========================  **/
var tabBulles = []; 

function bulleInfo ( infos ) 
{ 
	var bulle = create("div", {className:"bulle_info"} );
	tabBulles.push(bulle);
    
	// capture du texte entre les balises <script>
	var tab_scripts = infos.match(/<script[^>]*>([\s\S]*?)<\/script>/g);
    infos += "<a href='javascript:do_nothing();' id='control_bulle' style='color:#000;'></a>";
    
	bulle.innerHTML = infos;
    
	if( tab_scripts )
        for(var i=0, len=tab_scripts.length ; i < len ; i++)	
            globaleval(tab_scripts[i].replace(/^<script[^>]*>/, "").replace(/<\/script>$/, ""));
	
    // Récupère le focus par le survol de la souris
    bulle.onmouseover =    function(e)
                            {
                                if( tabBulles[tabBulles.length-1] != bulle ) return;
                                if(!e) var e = window.event;
                                                                
                                $('control_bulle').focus();                                
                            }
    // Si en dehors survol de la souris
	bulle.onmouseout   =   function (e) 
                            {
                            	if( tabBulles[tabBulles.length-1] != bulle ) return;                            	
                            	if(!e) var e = window.event;
                                
                            	var tg     = (window.event)    ? e.srcElement      : e.target;
                            	var reltg  = (e.relatedTarget) ? e.relatedTarget   : e.toElement;
                            	
                                while (reltg && reltg != tg && reltg != bulle )
                            		reltg= reltg.parentNode;
                            	
                                if(reltg == tg || reltg == bulle ) return;
                                
                                drop=0;
                            	tabBulles.pop();
                            	bulle.destroy();
                            }
    
    bulle.accrocher($("corps"));
    
	var x0     = $("corps").offsetLeft;
	var xMax   = x0 + 800;
	var x      = souris.x;
   
	if( x > x0 ) x = x0 + ( (x-x0)*800 / ( 800 + bulle.offsetWidth ) );
    
	var y  = (souris.y) - ( ( (souris.y - dim_window.scrollTop()) * bulle.offsetHeight) / dim_window.height() );
    
    
	bulle.style.left   = Math.round(x)+"px"; /* Suppression des décimales par Math.floor */
	bulle.style.top    = Math.round(y)+"px"; /* Suppression des décimales par Math.floor */
       	
	//return  bulle;
}

/*  -----------------  createurs de bulles d'informations  -----------------  */
function flotte ( num, type, parent, joueurId ) 
{
	ajax(  "ajax.php", 
           "GET", 
           "flotte="+num+"&type="+type+(joueurId?"&joueurId="+joueurId:""), 
           function(xhr){ bulleInfo( xhr.responseText, parent ); }, 
           true     );
}
function mission ( num, type, planeteId, planeteNom ) 
{
	ajax(  "ajax.php", 
           "GET", 
           "mission="+num+"&missionType="+type+"&planeteId="+planeteId+"&planeteNom="+planeteNom, 
           function(xhr){ bulleInfo( xhr.responseText ); }, 
           true     );
}
function unite ( id, parent, bonus, vitesse ) 
{
	if( id==212 ) batiment(id);			// station solaire
	else ajax( "ajax.php", 
               "GET", 
               "unite="+id+"&bonus="+( bonus ? bonus : "0")+"&vitesse="+( vitesse ? vitesse : "0"), 
               function(xhr){  bulleInfo( xhr.responseText, parent ); }, 
               true     );
}
function planete ( id, prec ) 
{
	ajax(  "ajax.php", 
           "GET", 
           "planete="+id+(prec?"&precedent="+prec:""), 
           function(xhr){ bulleInfo( xhr.responseText ); }, 
           true     );
}
function planeteVide ( g, s, p ) 
{
	ajax(  "ajax.php", 
           "GET", 
           "planeteVide="+p+"&systeme="+s+"&galaxie="+g, 
           function(xhr){ bulleInfo( xhr.responseText ); }, 
           true     );
}
function lune ( id ) 
{
	ajax(  "ajax.php", 
           "GET", 
           "planete="+id+"&lune", 
           function(xhr){ bulleInfo( xhr.responseText ); }, 
           true     );
}
function batiment ( id ) 
{
	ajax(  "ajax.php", 
           "GET", 
           "batiment="+id, 
           function(xhr){ bulleInfo( xhr.responseText ); }, 
           true     );
}
function recherche ( id ) 
{
	ajax(  "ajax.php", 
           "GET", 
           "recherche="+id, 
           function(xhr){ bulleInfo( xhr.responseText ); }, 
           true     );
}
function officier ( id ) 
{
	ajax(  "ajax.php", 
           "GET", 
           "officier="+id, 
           function(xhr){ bulleInfo( xhr.responseText ); }, 
           true     );
}
function joueur ( id, prec ) 
{
	ajax(  "ajax.php", 
           "GET", 
           "joueur="+id+(prec?"&precedent="+prec:""), 
           function(xhr){ bulleInfo( xhr.responseText ); }, 
           true     );
}
function alliance ( id ) 
{
	ajax(  "ajax.php", 
           "GET", 
           "alliance="+id, 
           function(xhr){ bulleInfo( xhr.responseText ); }, 
           true     );
}
function debris ( num, tab ) 
{
	ajax(  "ajax.php", 
           "GET", 
           "debris="+num+"&tab="+tab, 
           function(xhr){ bulleInfo( xhr.responseText ); }, 
           true     );
}
function envoyerSonde ( p, type ) 
{
	ajax(  "ajax.php", 
           "GET", 
           "envoyerSonde="+p+"&type="+type, 
           function(xhr){ bulleInfo(xhr.responseText);}, 
           true     );
}

function confirmSuppr ( lien ) 
{
    drop++;
    message =   '<p>Etes vous sur ?</p>';
    annule  =   ' <a href="javascript:tabBulles[tabBulles.length-1].destroy();" onclick="drop=0">Non</a>';
    
    if(drop==1)
    {
        bulleInfo(  message + lien + annule );  
    }  
}
/*  -----------------  fonctions via ajax et pop up -----------------  */
function changerPlanete ( num ) {
	ajax("ajax.php", "GET", "changerPlanete="+num,  function(xhr){window.location.href="?url="+URL;}, true);
}
function redirection(lien)
{
    window.location.href="?url="+lien;
}
/**
 * deux surcharges :
 *  [missionClassique] , planeteId
 *  [explo|colo] , pPos, sPos, g
 */
function nouvelleMission ( type, planeteId, systemePos, galaxie ) 
{
	var url = window.location+'';
	var page = url.replace(/^.+\?url=/, '');

	ajax("ajax.php?url=fleet.php&choixFlotte="+type+"&planete="+planeteId+"&systeme="+systemePos+"&galaxie="+galaxie, "POST",
		"precedent="+page,
		function(xhr){ bulleInfo(xhr.responseText);},
		true
	);			
}

function rapportCombat ( id ) {
	window.open('animationCombat.php?id='+id, 'Rapport de combat',
		config='toolbar=no, menubar=no, location=no, scrollbars=yes, directories=no, resizable=yes, width=800, height=600;');
}

function ecrireMessage ( id, prec ) {
	ajax("ajax.php", "GET", "url=messages.php&ecrire="+id+(prec?"&precedent="+prec : ""), function(xhr){ bulleInfo(xhr.responseText);}, true);
}

function capteurs ( p ) {
	window.open('./capteurs.php?p='+p, 'Phalange de capteurs',
		config='toolbar=no, menubar=no, location=no, scrollbars=yes, directories=no, resizable=yes, width=700, height=600;');
}

/*********************************************************************************/
/** FONCTION VISUALISATION DE L'OBJET                                           **/
/*********************************************************************************/
function visualiser(objet,image)
{  
    var obj = document.getElementById(objet);
    var img = document.getElementById(image);
    
    if(obj.style.display == 'none')
    {    
       if(obj.id.substring(0,3) == 'bug')
       {    
            obj.style.display      = 'block';          
            sonID('afficheBug').value = "Cacher";
       }    
       else  obj.style.display      = "table";

       if(img)img.src   = "img/fleche_haut.png";
    } 
    else
    {   
        if(obj.id.substring(0,3) == 'bug')sonID('afficheBug').value       = "Afficher";      
        obj.style.display    = 'none';       

        if(img)img.src   = "img/fleche_bas.png";
    }    
}

/*********************************************************************************/
/** FONCTION DEFILEMENT HEURE                                                   **/
/*********************************************************************************/

// Déclaration des constantes 
var esp		=	1;
var maxi	=	40;		//point d'arrivée du texte
var mini	=	10;		//point de départ du texte
var aa		=	mini;
// Déclaration des variables 
var a_mini,a_maxi,timing,h_digith,heu,min,sec,heure,min;

function Heure(reverse) 
{
	/* La variable reverse renvoi votre choix:
	** - 0 pour l'heure classique de 0 à 24H
	** - 1 pour l'heure inversée  de 24 à 0H'
	********************************************/
	h 		= 	new Date();
	
	if(reverse == 0 || reverse <0 || reverse >1 )
	{
		/** Choix de l'heure classique **/
		heu 	= 	h.getHours();
		min 	= 	h.getMinutes();
		sec 	= 	h.getSeconds();	
	}
	if(reverse == 1)
	{
		/** Choix de l'heure inversée **/
		heu 	= 	-(h.getHours()-23);
		min 	= 	-(h.getMinutes()-59);
		sec 	= 	-(h.getSeconds()-59);
	}
	
	excH	=	heu<10; 	// exception si inférieur à 10
	excM	=	min<10;		// exception si inférieur à 10
	excS	=	sec<10;		// exception si inférieur à 10
	a_mini	=	aa==mini;
	a_maxi	=	aa==maxi;
		
	if( excH ) heu		= 	"0"+heu;	// si excep° OK alors '0' sur chiffree   
	if( excM ) min 		= 	"0"+min;	// ex: 07:08:06 à la place de 7:8:6      
	if( excS ) sec 		= 	"0"+sec;	/***************************************/
	if( a_mini ) esp	= 	1;			// quand on arive à mini on incrémente a 
	if( a_maxi ) esp	= 	-1;			// quand on arrive à maxi on décrémente a
	
	aa		=	aa+esp;
	h_digit	=	heu+":"+min+":"+sec;	// Modification en heure "digitale" (00:00:00)
	b		=	aa;
	
	while(b-->0)
	h_digit						=	" "+h_digit;// génère des espaces qui font le défilement
	sonID("heure_defil").innerHTML	=	h_digit;	// affichage dans un conteneur nommé "heure"
				 
	/* on effectue la fonction toutes les 50 millièmes de seconde, si vous    */
	/* voulez un défilement plus ou moins rapide changer la valeur de timing  */
	/**************************************************************************/ 
	timing	=	50;	
	setTimeout("Heure("+reverse+");",timing);	// Boucle temporelle
} 
/**  =========================  GENERAL  =========================  **/