// config
var value2;
var value3;
page = window.location.pathname;
page = page.split("/");
page = page[page.length - 1];
// timers
plistInterval = 120000;
contentType = '';
msg_check = '<span class="black">Analyse en cours...</span>';
msg_checkprocess = 'Analyse d\'un champ en cours, veuillez patienter !';
msg_empty = 'Certains champs sont vides, veuillez vérifier votre saisie !';
msg_success_login = '<span class="success_login"><img src="'+fullpath+'img/ajax-loader.gif" alt="" /> Connexion réussie ! Redirection en cours...</span>';
msg_success_logout = '<span class="success_login"><img src="'+fullpath+'img/ajax-loader.gif" alt="" /> D&eacute;connexion effectu&eacute;e ! Redirection en cours...</span>';
msg_notincache = 'Cette infobulle n\'est pas encore dans le cache de l\'Armurerie, affichage impossible. :(';
prefix_loading = '<span class="center bold"><img src="'+fullpath+'img/ajax-loader_bar.gif" alt="" /><br /><br />';
suffix_loading = '</span>';
valid_pic = '<img src="'+fullpath+'img/valid.png" class="valid_pic" alt="" />';
err_unavailable_forumname = 'Le nom de compte jeu que vous avez choisi n\'est pas disponible sur le forum, vous devez en sélectionner un autre pour le forum.';
err_field_errors = 'Vous ne pouvez pas valider le formulaire tant qu\'il comporte des erreurs !';
err_field_empty = 'Vous ne pouvez pas valider le formulaire, certains champs sont vides !';
err_field_file_error = 'Vous ne pouvez pas valider le formulaire tant que l\'envoi des fichiers n\'est pas validé !';
$news_type = new Array("news.all/3","news.comm/3","news.tech/3");
$regles_type = new Array("regles.19","regles.20","regles.21","regles.22","regles.23","regles.24");

switch(page)
{ 
 case 'index': case '':
  contentType = 'news';
 break;
 case 'regles':
  contentType = 'regles';
 break;
}

// charge la liste des connectés
function pList(realm,timer){
 if (timer > 0)
 {
  plistInterval = timer;	 
 }
 if (page == 'playerlist-'+realm)
 {
  getPlist = function(){
   loadingMessage('#pl_'+realm,'Chargement de la liste des connectés...');	  	 	
   $.post(fullpath+'playerlist/', {serveur: realm}, function(data){
    $('#pl_'+realm).html(data);
   });
  }
  getPlist();
  var refreshR = setInterval(getPlist, plistInterval);
 }
}
// rafraichit la liste des connectés des deux serveurs
function refreshRealms(){
 pList('gloriam',0);
 pList('vitam',0);
}
// affiche un message de chargement personnalisé
function loadingMessage(cont,message){
 $(cont).html(prefix_loading+message+suffix_loading);	
}
// gestion des cookies
function createCookie(name,value,minutes){
 if (minutes) {
  var date = new Date();
  date.setTime(date.getTime()+(minutes*60*1000));
  var expires = "; expires="+date.toGMTString();
 }
 else var expires = "";
 document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name){
 var nameEQ = name + "=";
 var ca = document.cookie.split(';');
 for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
 }
 return null;
}
function eraseCookie(name){
 createCookie(name,"",-1);
}
// gestion du formulaire de connexion
function doLogin(form_cont){
 user = $('input[name=user]').get(0).value;
 pass = $('input[name=pass]').get(0).value;
 
 if (user != '' && pass != '')
 {
  $.post(fullpath+'login/', {user: user,pass: pass,interface: interface}, function(data){
   if (data == 'ok')
   {
	$('#'+form_cont).html(msg_success_login);  
	reloadPage(3); 
   }
   else
    alert(data);	  
  });	  	 
 }
 else
  alert(msg_empty);	
}
// déconnexion
function doLogout(cont,jQ){
 jQ.post(fullpath+'logout/', function(data){
  jQ('.user_panel').html('');  
  jQ('.user_panel').append('<span id="'+cont+'"></span>');  
  jQ('#'+cont).html(msg_success_logout);  
  reloadPage(3); 
 });
}
// recharge la page
function reloadPage(delay){
 if (delay == 0)
  document.location.reload();
 else
  timeOut = setTimeout('document.location.reload()',delay*1000); 	
}

// charge le contenu des onglets dynamiques
function tabLoad(contentType){
 switch(contentType)
 {
  case 'armurerie':
   arrayCat = $armo_type;
   patternLoad = "armo";
   contClass = ".armoli";
   loadContainer = "#armory_cont";
   tabColor = "#248fcc";
   tabSelColor = "#56d6e5";   
   if (typeof(p_faction) != 'undefined')
   {
    switch(p_faction)
    {
	 case 1:   
      tabColor = "#e4030d";
      tabSelColor = "#f7a234";
     break;   
    }
   }
  break;
  case 'news':
   arrayCat = $news_type;
   patternLoad = "news";
   contClass = ".newsli";
   loadContainer = "#news_block";
   tabColor = "#515189";
   tabSelColor = "#000";
  break;
  case 'regles':
   arrayCat = $regles_type;
   patternLoad = "regles";
   contClass = ".reglesli";
   loadContainer = "#regles_block";
   tabColor = "#036";
   tabSelColor = "#000";
  break;
 }
 idSelected = '';	
 defLoad = arrayCat[0];
 $(contClass).click(function(){
  idSelected = $(this).attr('id').replace(patternLoad, '');	 
  $(contClass).each(function(){							  
   id = $(this).attr('id').replace(patternLoad, '');
   if (id != idSelected)
   {	
	$Load_cont = $(loadContainer).load(arrayCat[idSelected]);
	$('#'+patternLoad+idSelected).css("color",tabSelColor);
	$('#'+patternLoad+id).css("color",tabColor);
   }
  });
 });
 if (idSelected == '')
 {  
  $Load_cont = $(loadContainer).load(defLoad);	
  $('#'+patternLoad+'0').css("color",tabSelColor);
 }
}
// slider header
function initSlider(jQ){	
 jQ('#slider').premium({
	'itemsSelector' : '.thumbnails li',
	'viewsSelector' : '.fullviews .item',
 });	
}
// retourne l'item du slider sélectionné
function getSliderIndex(jQ){
 index = '';	  
 while (index == '')
 {
  jQ('.item').each(function(){	 
   cont_id = jQ(this).attr('id');   
   if (jQ(this).css('display') != 'none')
   {
	index = cont_id;
   }
  });
 }
 
 return index;	  
}
// lie les actions sur les zones réactives au slider
function bindSliderEvents(jQ){
 jQ('#big_pic').hover(function(){
  currentIndex = getSliderIndex(jQ);
  currentLink = jQ('.slide_link-'+currentIndex).attr('href');
  if (currentLink != undefined)
  {
   jQ('.item a').addClass('hover');	  
   jQ(this).css('cursor','pointer');	
   jQ(this).attr('href',currentLink);
  }
 },function(){
  jQ('.item a').removeClass('hover');
  jQ(this).css('cursor','default');	
  jQ(this).removeAttr('href');
 });
 jQ('.thumb').each(function(){
  jQ(this).click(function(){
   cont_id = jQ(this).attr('id');	  
   jQ(".show-"+cont_id).trigger('click');
  })
  .hover(function(){
   cont_id = jQ(this).attr('id');	  
   jQ(".show-"+cont_id).trigger('mouseenter');
  }, function(){
   cont_id = jQ(this).attr('id');	  
   jQ(".show-"+cont_id).trigger('mouseleave');
  });
 });
}
// gère les erreurs de champs
function field_error(field,action,s_var){
 $.post(fullpath+'field/', {type: 'error',field: field, action: action, s_var: s_var}); 
}
// récupère la valeur d'un champ sauvegardé
function field_get(field,var_nb){
 $.post(fullpath+'field/', {type: 'get',field: field}, function(data){if (var_nb == 2)value2 = data;else value3 = data;});
}
// sauvegarde les données de champs
function field_save(field_type,infos,check_type){
 if (field_type == 'game' || field_type == 'recovery')	
  $.post(fullpath+'field/', {type: 'save',field_type: field_type,infos: infos}); 	
 else
  $.post(fullpath+'field/', {type: 'save',field_type: field_type,infos: infos,check_type: check_type}); 	
}
// nettoie les données de formulaire enregistrées
function field_unset(notregister){
 if (notregister)
  $.post(fullpath+'field/', {type: 'unset',field: 'special'});
 else	
  $.post(fullpath+'field/', {type: 'unset'});
}
// met à jour les étapes en haut de page
function newacc_switchStep(number){
 $('.step').each(function(){
  step_id = $(this).attr('id').replace('step',''); 
  if (step_id == number)
   $(this).addClass('active');
  else if (step_id < number)
   $(this).removeClass('active').addClass('done');
 });
}
// vérifie les informations soumises
function newacc_doCheck(field,value,type,s_var){
 $('#check_'+type+'_'+field).html(msg_check);
 if (value == '')	
 {
  $('#check_'+type+'_'+field).html('Ce champ ne peut pas être vide.');	 
  field_error(field,'set',s_var);
 }
 else
 {
  switch(field)
  {
   case 'pass':
    value2 = $('input[name=game_acc]').get(0).value;
   break;	  
   case 'pass_bis':
    value2 = $('input[name=game_pass]').get(0).value;
   break;
   case 'email_bis':
    value2 = $('input[name=game_email]').get(0).value;
   break;	
   case 'forum_acc':
    field_get('account',2);
   break;
   case 'forum_pass':
    value2 = $('input[name=forum_acc]').get(0).value;
	field_get('pass',3);
   break;	
   case 'forum_pass_bis':
    value2 = $('input[name=forum_pass]').get(0).value;
   break;
   case 'forum_display':
    same_infos = $('input[type=checkbox][name=same_infos]:checked').attr('value');
	if (same_infos != undefined)
	 field_get('account',2);
	else
	 value2 = $('input[name=forum_acc]').get(0).value; 
	field_get('account',3); 
   break;	
   case 'acc_link':
    value2 = type;
   break;
  }
  $.post(fullpath+'loader/',{action: 'formcheck',field: field,value: value,value2: value2,value3: value3,s_var: s_var}, function(data){
   if (data == 'ok')
   {
	field_error(field,'unset',s_var);
    $('#check_'+type+'_'+field).html(valid_pic);
   }
   else	
   {
	field_error(field,'set',s_var);   
    $('#check_'+type+'_'+field).html(data);
   }
  });
 }
}
// gère les différentes étapes de la création de compte
function newacc_doStep(number){
 switch(number)
 {
  case 1:
   field_unset(false);
   $.post(fullpath+'loader/',{action: 'cgu'}, function(data){$('#newacc_cont').html(data);});  
  break;
  case 2:
   valid_cgu = $('input[type=checkbox][name=cgu]:checked').attr('value');
   if (valid_cgu != undefined)
   {
	newacc_switchStep(number);   
	$('#newacc_cont').hide('fast');
    $.post(fullpath+'loader/',{action: 'game_acc'}, function(data){$('#newacc_cont').html(data);});
	$('#newacc_cont').show('slow');
   }
   else
    alert('Vous devez cocher la case ci-dessus avant de continuer !');
  break;
  case 3:
   $.post(fullpath+'field/',{type: 'error',action: 'check',s_var: 'register'}, function(data){
	if (data == 'ok')
	{
	 account = $('input[name=game_acc]').get(0).value;	
	 pass = $('input[name=game_pass]').get(0).value;
	 email = $('input[name=game_email]').get(0).value;
	 captcha = $('input[name=game_captcha]').get(0).value;
	 if (account == '' || pass == '' || email == '' || captcha == '')
	 {
	  alert(err_field_empty);	 
	  return false;
	 }
	 infos = account+' | '+pass+' | '+email;
	 field_save('game',infos,'');	
	 newacc_switchStep(number);
	 $('#newacc_cont').hide('fast');
	 $.post(fullpath+'loader/',{action: 'forum_acc'}, function(data){
	  $('#newacc_cont').html(data);
	  $.post(fullpath+'loader/',{action: 'checkforum'}, function(data){
	   if (data != 'ok')
	   {
		alert(err_unavailable_forumname);  
		$('.forum_infos').css('display','block'); 
		$('input[type=checkbox][name=same_infos]').attr('disabled','disabled');
		$('input[type=checkbox][name=same_infos]').removeAttr('checked');
	   } 	  
	  });
	 });
	 $('#newacc_cont').show('slow');
	}
	else
	 alert(err_field_errors); 
   }); 
  break;
  case 4:
   checked = $('input[type=checkbox][name=same_infos]:checked').attr('value');
   check_type = (checked != undefined)?'partial_check':'check';
   $.post(fullpath+'field/',{type: 'error',action: check_type,s_var: 'register'}, function(data){
	if (data == 'ok')
	{	
	 display = $('input[name=forum_display]').get(0).value;	
	 display_check = $('#check_forum_display').html();
	 if (display == '')
	 {
	  alert(err_field_empty);	 
	  return false;
	 }	 
	 if (check_type == 'check')
	 {
      account = $('input[name=forum_acc]').get(0).value;	
	  pass = $('input[name=forum_pass]').get(0).value;
	  if (account == '' || pass == '')
	  {
	   alert(err_field_empty);	 
	   return false;
	  }	 
	  infos = account+' | '+pass+' | '+display;
	 }
	 else
	  infos = display; 
	 if (display_check == msg_check)
	  alert(msg_checkprocess);
	 else
	 { 
	  field_save('forum',infos,check_type);
	  loadingMessage('#newacc_cont','Création de vos comptes en cours, veuillez patienter...');
	  $.post(fullpath+'loader/',{action: 'valid_create'}, function(data){
	   $('#newacc_cont').html(data);
	   newacc_switchStep(number);   	 
	  });
	 }
	}
	else
	 alert(err_field_errors);
   });
  break;	 
 }	 
}
// affiche/masque les champs nom de compte/pass forum
function forum_toggleDisplay(){
 if ($('.forum_infos').css('display') == 'none')	
  $('.forum_infos').show('fast');
 else
  $('.forum_infos').hide('fast');
}
// ferme une modalbox au bout de X secondes
function closeBox(sec,doreload){
 if (parent.interface != 'forum')
  closeBox = setTimeout('parent.$.prettyPhoto.close()',sec*1000);
 else 
  closeBox = setTimeout('parent.j.prettyPhoto.close()',sec*1000);
 if (doreload)
 {
  delay = parseInt(sec+0.5);	 
  reloadPage = parent.setTimeout('reloadPage()',delay*1000);
 }
}
// charge une lightbox en fonction de l'erreur rencontrée (mauvais pass ou compte non lié)
function handleLinkError(error,j){
 error = error.split('-');
 switch(error[0])
 {
  case 'unlinked':
   var hideCookie = readCookie('hideBox');
   if (!hideCookie)
   {   
    page_load = 'loader-unlinked-'+error[1]+'/';
	openBox = setTimeout('j.prettyPhoto.open(fullpath+page_load+\'?iframe=true&width=900&height=220\');',2000);
   }
  break;
  case 'pass':
   page_load = 'loader-pass-'+error[1]+'/';
   openBox = setTimeout('j.prettyPhoto.open(fullpath+page_load+\'?iframe=true&width=900&height=150\')',2000);
  break;
  default:
   return false;
  break; 	 
 }	
}
// lie deux comptes
function doLink(acc_type){
 account = $('input[name='+acc_type+'_acc_link]').get(0).value;	
 pass = $('input[name='+acc_type+'_pass_link]').get(0).value;
 
 if (account == '' || pass == '')
 {
  alert(err_field_empty);	 
  return false;
 }
 else
 {
  field_unset(true);	 
  $.post(fullpath+'field/',{type: 'error',action: 'check',s_var: 'site'}, function(data){
   if (data == 'ok')
   {
	infos = account+'||'+pass;   
	$.post(fullpath+'loader/',{action: 'authenticate',acc_type: acc_type,infos: infos}, function(data){
	 if (data == 'ok')
	 {
	  $.post(fullpath+'loader/',{action: 'dolink',acc_type: acc_type,account: account}, function(data){
	   if (data == 'ok')
	   {
	    loadingMessage('#light-cont','Comptes liés avec succès !<br /><br />Fermeture de la fenêtre...');
	    closeBox(4,true);
	   }
	  });
     }
	 else if (data == 'lock')
	 {
	  loadingMessage('#light-cont','Echec du lien des deux comptes, le compte a été mis en liste noire, veuillez contacter un administrateur.<br /><br />Fermeture de la fenêtre...');
	  closeBox(4);
	 }
	 else
	  alert(data);
	});
   }
   else
	alert(err_field_errors);
  });
 }
}
// repousse l'affichage de la fenêtre de linking
function delayLink(hours)
{
 minutes = hours*60;
 createCookie('hideBox','1',minutes);	
 alert('Choix mémorisé !');
 closeBox(0.5);
}
// confirme le nouveau mot de passe d'un compte
function doConfirm(acc_type)
{
 pass = $('input[name='+acc_type+'_pass_confirm]').get(0).value;	
 
 if (pass == '')
 {
  alert(err_field_empty);	 
  return false;
 }
 else
 {
  $.post(fullpath+'loader/',{action: 'authenticate',acc_type: acc_type,infos: pass,type: 'pass'}, function(data){
   if (data == 'ok')
   {
	loadingMessage('#light-cont','Nouveau mot de passe valide !<br /><br />Fermeture de la fenêtre...');
	closeBox(3,true);
   }
   else if (data == 'lock')
   {
	loadingMessage('#light-cont','Le lien entre votre compte jeu et votre compte forum a été coupé.<br /><br />Fermeture de la fenêtre...');
	closeBox(4);
   }
   else
	alert(data);
  });
 }
}
// gère les votes
function doVote(step)
{
 account = $('input[name=game_acc_vote]').get(0).value;	
 account_check = $('#check_game_acc_vote').html();
 switch(step)
 {
  case 1:
   if (account == '')
   {
    alert(err_field_empty);	 
    return false;
   }
   else
   {
	if (account_check == msg_check)
	 alert(msg_checkprocess);
	else
	{   
	 $.post(fullpath+'field/',{type: 'error',action: 'check',s_var: 'site'}, function(data){
      if (data == 'ok')
      {	 
	   $.post(fullpath+'vote',{step: '2',account: account}, function(form){
	    $('#light-cont').html(form); 	  
	   });
	  }
	  else
	   alert(err_field_errors);
	 });
	}
   }
  break;	 
  default:
   return false;
  break;
 }
}
// lance un vote
function launchVote(root_id,root_url){
 $.post(fullpath+'loader/',{action: 'setvote',root_id: root_id}, function(data){
  $('#vote'+root_id).html('Vos points seront crédités dans 5 minutes.');
 });
 window.open(root_url,'','width=1000,height=700'); 	
}
// affiche une infobulle à partir d'une balise title
function hoverTooltip(jQ){
 jQ('.infobulle').hover(function(){	
  jQ('body').append('<span class="tooltip"></span>');
  var tooltip = jQ('.tooltip:last');
  tooltip.append(jQ(this).attr('title'));
  jQ(this).attr('title','');
  var posTop = jQ(this).offset().top-15;
  var posLeft = jQ(this).offset().left+jQ(this).width()-5;
  tooltip.css({left: posLeft,top: posTop});
  tooltip.show();
 },function(){	
  var tooltip = jQ('.tooltip:last');
  jQ(this).attr('title',tooltip.text());
  tooltip.remove();
 });
}
// gestion des favoris
function doFav(guid,realm,account,action_type,type){
 if (guid != '' && realm != '' && account != '' && (action_type == 'add' || action_type == 'remove') && type != '')
 {
  $.post(fullpath+'loader/',{action: 'fav',guid: guid,realm: realm,account: account,action_type: action_type,type: type}, function(data){
   alert(data);
  });	 
 }
 else
 {
  alert(err_field_empty);	 
  return false;	 
 }
}
// affiche une infobulle de profil d'armurerie
function armoryTooltip(jQ){
 jQ('.armory_tooltip').hover(function(){	
  link_rel = jQ(this).attr('rel');
  profile_infos = link_rel.split('-');
  link_offset_t = jQ(this).offset().top;
  link_offset_l = jQ(this).offset().left;
  link_w = jQ(this).width();
  tooltip_cont = jQ('#'+link_rel).html();
  if (tooltip_cont != null)
  {
   var tooltip = jQ('#'+link_rel);
   var posTop = link_offset_t-tooltip.height()-5;
   var posLeft = link_offset_l+link_w+25;
   tooltip.css({left: posLeft,top: posTop});
  }
  else
  {
   jQ('body').append('<span class="armory_profile" id="'+link_rel+'"></span>');
   var tooltip = jQ('#'+link_rel);
	  
   if (profile_infos[3] == 'cached')
   {	  
    jQ.post(fullpath+'loader/',{action: 'getTooltip',type: profile_infos[2],id: profile_infos[0],realm: profile_infos[1]}, function(data){
     if (data != '')
      tooltip.html(data);
     var posTop = link_offset_t-tooltip.height()-5;
     var posLeft = link_offset_l+link_w+25;
	 tooltip.css({left: posLeft,top: posTop});
    });
   }
   else
   {
    tooltip.html(msg_notincache);
	var posTop = link_offset_t-tooltip.height()-5;
    var posLeft = link_offset_l+link_w+25;
	tooltip.css({left: posLeft,top: posTop});
   }
  }
  tooltip.show();
 },function(){	
  jQ('.armory_profile').hide();
 });
}

// chargement domReady
function initPortal(jQ){	
 jQ("a[rel^='prettyPhoto']").prettyPhoto({callback: function(){var pointsBox = readCookie('pointsBox');if (pointsBox){reloadPage(1);eraseCookie('pointsBox');}}});
 jQ.post(fullpath+'statut/',{interface: interface,realm: 'gloriam'}, function(data){jQ('#gloriam').html(data);});
 jQ.post(fullpath+'statut/',{interface: interface,realm: 'vitam'}, function(data){jQ('#vitam').html(data);});
 if (logged == 0)
  jQ('#userbar_login').keypress(function(event) {if (event.which == '13') jQ('#login_but').trigger('click');});
 else
 {	 
  jQ(".user_manage").click(function() {jQ('#user_menu').toggle('slow');}); 
  jQ('#user_menu').mouseleave(function() {jQ(this).hide('fast');});
 }
 if (contentType != '' && interface == 'site')
  tabLoad(contentType); 
 initSlider(jQ);
 bindSliderEvents(jQ);
 if (page == 'playerlist-gloriam' || page == 'playerlist-vitam')
  refreshRealms();
 jQ('.toggle').click(function() {
  toggle_id = jQ(this).attr('id');	 
  jQ('#toggled'+toggle_id).slideToggle();
 });
 if (page == 'newaccount')
 {
  newacc_doStep(1);
  jQ('#newacc_cont').keypress(function(event) {if (event.which == '13') jQ('.nextstep').trigger('click');});
 }
 if (acc_error != '' && page != 'newforumacc')
  handleLinkError(acc_error,jQ);
 jQ('#vote').click(function(){jQ.prettyPhoto.open(fullpath+'vote?iframe=true&width=700&height=180');}); 
 jQ('#point').click(function(){jQ.prettyPhoto.open(fullpath+'compte/addpoints?iframe=true&width=900&height=530');});
 hoverTooltip(jQ);
 armoryTooltip(jQ);
}
