var membre_id;
var id_test;

/*************** Objet des messages *****************/
var Message = Class.create();
Message.prototype={
	initialize: function(id,msg,width){
		this.id = id;
		this.msg = msg;
		this.width = width;
	},

	display: function(){
		$(this.id).setStyle({'width':this.width + "px"});
		afficheCentre(this.id);
		$(this.id).update(this.msg);
		//Deux fois, je sais pas pourquoi
		afficheCentre(this.id);
		Effect.Fade(this.id,{duration: 3.0});
	}
}
/************************************************/

//AUTRES
/**
* Détermination du navigateur
*/
function detnav() {
	var p,nav,ver; // variables locales
	var result = new Array();
	with(navigator.userAgent){
		switch(navigator.appName){
			case "Microsoft Internet Explorer" :
				nav='IE'; p=indexOf("MSIE"); ver= parseFloat(substring(p+5,p+9));
				if (indexOf("Opera")>-1){
					nav='Opera'; p=indexOf("Opera"); ver= parseFloat(substring(p+6,p+10));
				}
				break;
			case "Netscape" :
				nav='Netscape'; ver= parseFloat(substring(8,12));
				if (indexOf("Opera")>-1){nav='Opera'; p=indexOf("Opera"); ver= parseFloat(substring(p+6,p+10));}
				if (indexOf("Gecko")>-1){nav='Mozilla'; p=indexOf("rv:"); ver= parseFloat(substring(p+3,p+7));}
				if (indexOf("Netscape6")>-1){nav='Netscape6'; p=indexOf("Netscape6"); ver= parseFloat(substring(p+10,p+14));}
				if (indexOf("Firefox")>-1){nav='Firefox'; p=indexOf("Firefox"); ver= parseFloat(substring(p+8,p+12));}
				break;
			case "Opera" :
				nav='Opera'; p=indexOf("/"); ver= parseFloat(substring(p+1,p+5));
				break;
			default :
				nav='inconnu'; ver='';
		}
	}
	result[0]=nav; result[1]=ver;
	return result;
}

//Le nav
var nav = detnav();

/**
* Fonctions utiles js à travers le site
* @author Medion
*/
var maxrow;
var is_loggedin;

Array.prototype.in_array = function(search_term) {
	var i = this.length;
	if (i > 0) {
		do {
			if (this[i] === search_term) {
				return true;
			}
		} while (i--);
	}
	return false;
} 

/**
Teste si le nombre est un entier
@param  num
@return boolean
*/
function is_numeric(num){
	var exp = new RegExp("^[0-9-.]*$","g");
	return exp.test(num);
}

function getLoginPopup(){
	var position = Position.cumulativeOffset($('td_co'));
	var xpos = position[0];
	var ypos = position[1];

	affiche('login_popup');
	cache('login_error');
	if($('search_popup')) cache('search_popup');
	$('login_popup').setStyle({'top':ypos-8+'px','left': xpos-30 +'px'});
	$('login').focus();
}

function getSearchPopup(){
	if(!$('search_popup').visible()){
		var position = Position.cumulativeOffset($('ipb-tl-search'));
		var xpos = position[0];
		var ypos = position[1];

		$('search_popup').show();
		$('login_popup').hide();
		$('search_popup').setStyle({ 'top':parseInt(ypos+26)+'px','left': xpos-78 +'px'});
		$('search_mot').focus();
	}
	else{
		$('search_popup').hide();
		$('login_popup').hide();
	}
}

/*************************CO/Deco*************************************/
function connexion(){
	var params=$H({'login':$F($('login')),'pass':$F($('pass'))});
	var filename="../scripts_async/connexion.php";
	
	var ajax = new Ajax.Request(filename,
		{method: 'post',
			postBody: params.toQueryString(),
			onSuccess: function (requete){
				is_loggedin = 1;
				array_retour = eval(requete.responseText);
			
				if(array_retour[0]==1){
					if(array_retour[1]['skins_id']!=skin_image_dossier){
						var sURL = unescape(window.location.pathname);
						window.location.href = sURL;
					}
					
					$('bandeau_menu').update(array_retour[2]);
					
					cache('login_popup');
					
					var message = new Message("displayMsg","Vous êtes connecté!",200);
					message.display();
					membre_id = array_retour[1]['id'];
					
					//Page conrole other
					if(currentPage=="control_oth"){
						var params=$H({'action':'checkShowAff','mem1':membre_id,'mem2':membre_visu});
				
						var filename="../scripts_async/getComparaison.php";
						
						//ICI Code AJAX
						var ajax = new Ajax.Request(filename,
						{method: 'post',parameters:params,
							onSuccess: function (requete){
								var rep = requete.responseText;
								if(rep==1){						
									$('lien_aff').setAttribute('href','javascript:getAff('+membre_id+','+membre_visu+');');
									$('calc_aff').show();
									affIsLoaded = 0;
								}
							}
						});
					}
				}
				else if(array_retour[0]==0){
					affiche('login_error');
				}
				
				//Page fiche pr comm
				if(currentPage=="fiche"||currentPage=="news"||currentPage=="comm"||currentPage=="liv_or"){
					checkGuest = 0;
					
					if($('fiche_comm_supp')) $('fiche_comm_supp').hide();
					
					if(!array_retour[1]['is_admin']){
						$$('.mem_'+array_retour[1]['id']).each(function(s) {
							s.show();
						});
					}else{
						$$('.btn_del_com').each(function(s) {
							s.show();
						});
						$$('.btn_edit_com').each(function(s) {
							s.show();
						});
					}
				}
				if(currentPage=="fiche"){
					choseFiche($F($("fiche_jeu_sup")),$F($("fiche_jeu_rpg")));
				}
				//Page accueil
				if(currentPage=="accueil"){
					getLastPosts();
				}
			}
		});
}

function deconnexion(){	
	var filename = "../scripts_async/deconnexion.php";
	
	var ajax = new Ajax.Request(filename,
		{method: 'get',
			onSuccess: function (requete){
				if(access!=1){
					var url = "../";
					window.location.replace(url);
					var message = new Message("displayMsg","Vous êtes déconnecté!",200);
					message.display();
				}
				else{
					is_loggedin = 0;
					show_add_rpg = 0;
					$('bandeau_menu').update(requete.responseText);
					
					var message = new Message("displayMsg","Vous êtes déconnecté!",200);
					message.display();
					membre_id = "";
					
					//Page fiche pour comm et news
					if(currentPage=="fiche"||currentPage=="news"||currentPage=="comm"||currentPage=="liv_or"){
						checkGuest = 1;
						
						if($('fiche_comm_supp')) $('fiche_comm_supp').show();
						
						$$('.btn_edit_com').each(function(s) {
							s.hide();
						});
						$$('.btn_del_com').each(function(s) {
							s.hide();
						});
						cache('modif_com');
					}
					if(currentPage=="fiche"){
						$$('.add_collec').each(function(s) {
							s.hide();
						});
						$('add_rpg_fini').hide();
						$('add_rpg_todo').hide();
						$('rem_rpg_fini').hide();
						$('rem_rpg_todo').hide();
					}
					//Page fiche pr accueil
					if(currentPage=="accueil"){
						getLastPosts();
					}
					//Page fiche pr accueil
					if(currentPage=="control_oth"){
						$('calc_aff').hide();
					}						
				}
			}
		});
		
		
}

/*************************************************************/

//DOM
/**
* Affiche div/span
* @param html_id
*/
function affiche(html_id){
	$(html_id).show();
}

/**
* Cache une div/span donnée par son id
* @param html_id
*/
function cache(html_id){
	$(html_id).hide();
}

/**
* Affiche ou cache la div selon l'état
* @param html_id
*/
function gestionAffichage(html_id,show_hide){
	if(!$(html_id).visible()){
		$(show_hide).setAttribute('src', '../skins_images/'+skin_image_dossier+'/icones_globales/moins.gif');
	}
	else{
		$(show_hide).setAttribute('src', '../skins_images/'+skin_image_dossier+'/icones_globales/add.gif');
	}
	Effect.toggle(html_id,'BLIND',{duration : 0.5 });
}

/**
* Incrémente la valeur d'un compteur
* @param html_id
*/
function incremente(element){
	var nbre = parseInt(element.innerHTML);
	element.innerHTML = nbre + 1;
}

/**
* Décrémente la valeur d'un compteur
* @param html_id
*/
function decremente(element){
	var nbre = parseInt(element.innerHTML);
	element.innerHTML = nbre - 1;
}

/**
* Assigne l'option selected selon la value (et non l'index!!!) passé
* @param selectid, valeur
*/
function Select_Value_Set(formu,SelectName, Value) {
  eval('SelectObject = document.' + formu +'.'+ SelectName + ';');
  
	  for(index = 0; index < SelectObject.length; index++) {
	   if(SelectObject[index].value == Value)
	     SelectObject.selectedIndex = index;
	   }
}

/**
* Assigne l'option selected selon la value (et non l'index!!!) passé
* @param selectid, valeur
*/
function Select_Value_Set2(Select, Value) {  
	  for(index = 0; index < Select.length; index++) {
	   if(Select[index].value == Value)
	     Select.selectedIndex = index;
	   }
}

/**
*
*/
function inSelect(val,selectid){
	var is_in = false;

	for(var i=0;i<$(selectid).options.length;i++){
		if($(selectid).options[i].value == val){
			is_in = true;
			return is_in;
		}
	}
	
	return is_in;
}

/**
*
*/
function emptyList( selectid ){
	$(selectid).options.length = 0;
}

/**
* Récupérer valeur de radio button du form spécifié
* @param formu nom du formulaire, radioname nom du groupe radio
* @return valeur
*/
function getRadioValue(formu,radioname) {
	var valeur = "";
	var zeradio = document.forms[formu].elements[radioname];

	for (var i=0; i<zeradio.length;i++) {
		if (zeradio[i].checked) {
			valeur = zeradio[i].value;
		}
	}
	return valeur;
}

/**
* Setter la  valeur de radio button du form spécifié
* @param formu nom du formulaire, radioname nom du groupe radio, valeur nouvelle valeur
*/
function setRadioValue(formu,radioname,valeur) {
	var zeradio = document.forms[formu].elements[radioname];

	for(var i = 0; i < zeradio.length; i++) {
		zeradio[i].checked = false;
		if(zeradio[i].value == valeur.toString()) {
			zeradio[i].checked = true;
		}
	}
}

//-------------------------------------------------------------------------------------------------------------------------------------------------------//
//AJAX
/**
* Instance objet AJAX
*/
function getXhr(){
    var xhr = null; 
	if(window.XMLHttpRequest) // Firefox et autres
	xhr = new XMLHttpRequest(); 
	else if(window.ActiveXObject){ // Internet Explorer 
		try {
			xhr = new ActiveXObject("Msxml2.XMLHTTP");
		 } catch (e) {
		 xhr = new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
			else { // XMLHttpRequest non supporté par le navigateur 
			alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest..."); 
			xhr = false; 
		} 
     return xhr;
}

//-------------------------------------------------------------------------------------------------------------------------------------------------------//
/**
* Le parse proto chelou! Hand made
*/
function evalJSON(string){
	if(/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.test(string)) return eval('(' + string+ ')');
	else return 0;
}

/**
*
*/
function getLastPosts(){
	var params=$H({'action':'get_last_posts'});
	
	var filename="../scripts_async/gestionPosts.php";
		
	var ajax = new Ajax.Request(filename,
		{method: 'post',parameters:params,
			onSuccess: function (requete){ 				
				$('last_posts').update(requete.responseText);
			} 
		});
}

function search_rpg(){
	var reg1=new RegExp("&", "g");
	var reg2=new RegExp("#", "g");
	var reg3=new RegExp("\-", "g");
	var reg4=new RegExp("\/", "g");
	var reg5=new RegExp("[\.]", "gi");
	var search_mot = ($F($('search_mot')) == "" && $('autocomplete')) ? $F($('autocomplete')):$F($('search_mot'));
	if(document.forms['search_form']){
		if(document.forms['search_form'].type_search[0].checked == true){
			var type_search = 1;
		}else{			
			var type_search = 0;
		}
	}
	else{
		var type_search = 0;
	}
	setCookie("popup_type_search", type_search);
	
	window.location.href = "../rpg/liste_compendium.php?type_search="+type_search+"&mot="+((((search_mot.replace(reg1,'xxx')).replace(reg2,'yyy')).replace(reg3,'zrk')).replace(reg4,'qwz')).replace(reg5,'qqq');
}

 /**** LIB ****/
 function returnSize() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  var result = new Array(myWidth,myHeight);
  return result;
}

function windowCenter(myId) {
	var result=returnSize();
	var myWidth=result[0];
	var myHeight=result[1];
	var elementWidth=$(myId).offsetWidth;
	var elementHeight=$(myId).offsetHeight;
	var scrolls = getScrollXY();	
	//var myScrollLeft=document.documentElement.scrollLeft;
	var myScrollLeft=scrolls[0];
	//var myScrollTop=document.documentElement.scrollTop;
	var myScrollTop=scrolls[1];
	var posX=myScrollLeft+myWidth-myWidth/2-elementWidth/2;
	var posY=myScrollTop+myHeight-myHeight/2-elementHeight/2;
	//$(myId).setStyle({ 'left': posX+'px',  'top': posY+'px'});
	Element.setStyle(myId,{ 'left': posX+'px',  'top': posY+'px'});
}

function windowCenterNoScroll(myId) {
	var result=returnSize();
	var myWidth=result[0];
	var myHeight=result[1];
	var elementWidth=$(myId).offsetWidth;
	var elementHeight=$(myId).offsetHeight;
	var myScrollLeft=document.documentElement.scrollLeft;
	var myScrollTop=document.documentElement.scrollTop;
	var posX=myScrollLeft+myWidth-myWidth/2-elementWidth/2;
	var posY=myHeight-myHeight/2-elementHeight/2;
	//$(myId).setStyle({ 'left': posX+'px',  'top': posY+'px'});
	Element.setStyle(myId,{'left': posX+'px',  'top': posY+'px'});
}

function afficheCentre(id){
	windowCenter(id);
	Element.show(id);
	windowCenter(id);
}

function afficheCentreFixed(id){
	if(nav[0]!='IE' || (nav[0]=='IE' && nav[1]>6)) 	$(id).setStyle({'position':'absolute'});
	windowCenterNoScroll(id);	
	$(id).show();
	windowCenterNoScroll(id);	
	if(nav[0]!='IE' || (nav[0]=='IE' && nav[1]>6)) $(id).setStyle({'position':'fixed'});
}

/**
*
*/
function getEmo(idemo,maxrow,page){
	var idloading = ($('loading-fiche')) ? 'loading-fiche':'loading-top'; 

	afficheCentre(idloading);
	
	var action = (idemo=='listEmoEdit') ? "getEmoEdit":"getEmoAdd";
	
	var params=$H({'action':action,'idemo':idemo,'maxrow':maxrow,'page':page});
	
	var filename="../scripts_async/gestionEmo.php";
	
	var ajax = new Ajax.Request(filename,
	{method: 'post',parameters:params,
		onSuccess: function (requete){
			$(idemo).update(requete.responseText);
			$(idloading).hide();
		}
	});
}

/**
*
*/
function addEmo(id_add,smiley_code){	
	tinyMCE.execInstanceCommand(id_add, "mceInsertContent", false, smiley_code, true);
}

/**
*
*/
function getPageSize(){
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	
	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

/**
*
*/
function getScrollXY() {
		var scrOfX = 0, scrOfY = 0;
		if( typeof( window.pageYOffset ) == 'number' ) {
			//Netscape compliant
			scrOfY = window.pageYOffset;
			scrOfX = window.pageXOffset;
		} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
			//DOM compliant
			scrOfY = document.body.scrollTop;
			scrOfX = document.body.scrollLeft;
		} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) 		) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
		}
  return [ scrOfX, scrOfY ];
}

function spoil(myElem){
	if (myElem.nextSibling.style.display == "none"){
		myElem.nextSibling.style.display = "block";
	}
	else{
		myElem.nextSibling.style.display = "none";
	}
}

function spoil1(elem){
	Element.extend(elem);
	var nextElem = elem.next();

	if(nextElem.visible()){
		nextElem.hide();
	}
	else{
		nextElem.show();
	}
}

/**
*
*/
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}

function setCookie(cookieName, cookieValue){
	document.cookie = escape(cookieName) + '=' + escape(cookieValue);
};