var navigateur, chatCombat = false;

$(document).ready(function(){

	/**
	 *	Gestion des accordeons - Voir aussi la fonction addAccordeon
	 */
  $('.toggler').next().addClass('cache');
  $('.toggler:first').addClass('rouge');
  $('.toggler:first + div').removeClass('cache');;

  $('.toggler').click(function()	{

  		var addOrRemove = $(this).next().hasClass('cache') ? 'remove' : 'add';
	    $('.toggler').removeClass('rouge');
	    $('.toggler + div').slideUp('slow').addClass('cache');

	    $('> input:radio', this).attr('checked', true);

  		if(addOrRemove=='add')	{
    		$(this).removeClass('rouge');
    		$('+ div', this).slideUp('slow').addClass('cache');
    	}
    	else	{
    		$(this).addClass('rouge');
    		$('+ div', this).slideDown('slow').removeClass('cache');
    	}
  	}
  );

  /**
   *	Gestion des liens du menu haut
   */
  $('.lien_menu_haut').hover(
  	function()	{
  		$(this).find('img').attr('src', $(this).find('img').attr('src').replace('.png', '-rouge.png'));
  	},
  	function()	{
  		$(this).find('img').attr('src', $(this).find('img').attr('src').replace('-rouge', ''));
  	}
  );

  $('._blank').attr('target', '_blank');

	/**
	 *	Script affichant sous l'input $(this) la liste des joueurs matchant la chaîne dans un div
	 *	Utilisation : <input type="text" class="parchemin getJoueur" function="alert(idduj+nomSeigneur+nomRoyaume);" fieldToDisplay="nomSeigneur_nomRoyaume" minLength="3" />
	 */
  $('.getJoueur').live('keydown', function(event, close, valid)	{
  		var keyCode = event.keyCode;
  		if(keyCode==13)	{
  			$(this).trigger(event, false, true);
  			return false;
  		}
  	}
  ).live('keyup', function(event, close, valid, reload)	{
  		var THIS = $(this);	// On stocke l'input
  		var keyCode = event.keyCode;
			var functionToCall = $(this).attr('function');
			var fieldToDisplay = $(this).attr('fieldToDisplay');
			var minLength = $(this).attr('minLength');
			var marginAuto = $(this).attr('marginAuto')=='true' ? ' marginAuto' : '';
			var rechercheGuilde = $(this).attr('guilde')=='true' ? 'guilde' : '';
			var value = $(this).val();

			var left = $(this).position().left;
			var top = $(this).position().top;

			var alreadyDisplayed = $(this).next('.getJoueurResults').length==1;

			if(value.length>=minLength)	{

				if(!alreadyDisplayed) {
					$(this).after('<div class="getJoueurResults back_parchemin noir width200'+marginAuto+'" style="position:relative;left:\''+left+'px\';top:\''+top+'px\';"><div id="resultats">Chargement...</div></div>');
				}

		  	if(keyCode==40)	{	// Bas
					$('.getJoueurSurvol.selected').nextAll('.getJoueurSurvol:first').addClass('backFonce selected').prevAll('.selected:first').removeClass('backFonce selected');
				}
		  	else if(keyCode==38)	{	// Haut
					$('.getJoueurSurvol.selected').prevAll('.getJoueurSurvol:first').addClass('backFonce selected').nextAll('.selected:first').removeClass('backFonce selected');
				}
				else if(keyCode==13 || valid)	{	// Entree
					$('.getJoueurSurvol.selected').trigger('click');
				}
				else if(keyCode==27 || close)	{	// Echap
					$(THIS).val('');
					$('.getJoueurResults').remove();
				}

				else {
					$.post('../ajax/rechercheJoueur_ajax.php',
						{'chaine': escape(value), 'guilde': rechercheGuilde},
						function(data)	{
							var resultats = '<table class="width200"><tr><td class="grisFonce italique gauche petit">R&eacute;sultats</td></tr>';

							var nbResultats = 0;
							var premiereGuilde = true;
							var premierJoueur = true;
							$(data).find('resultat').each(function()	{
									var id = $(this).attr('id');
									var typeEnregistrement = $(this).attr('typeEnregistrement');

									var selected = nbResultats==0 ? ' selected backFonce' : '';

									if(typeEnregistrement == 'guilde') {
										var nomGuilde = $(this).find('nomGuilde').text();

										if(premiereGuilde) {
											resultats += '<tr><td class="italique gras tres_petit">Guilde(s)</td></tr>';
										}
										resultats += '<tr typeEnregistrement="'+typeEnregistrement+'" class="pointer getJoueurSurvol'+selected+'" id="'+id+'" nomGuilde="'+nomGuilde+'"><td>'+nomGuilde;

										$(this).find('membre').each(function() {
												resultats += '<span idJoueur="'+$(this).attr('idJoueur')+'" nomSeigneur="'+$(this).attr('nomSeigneur')+'" nomRoyaume="'+$(this).attr('nomRoyaume')+'"></span>';
											}
										);

										premiereGuilde = false;
									}

									else if(typeEnregistrement == 'joueur') {
										var nomSeigneur = $(this).find('nomSeigneur').text();
										var nomRoyaume = $(this).find('nomRoyaume').text();
										var nomGuilde = '';

										if(premierJoueur) {
											resultats += '<tr><td class="italique gras tres_petit">Joueur(s)</td></tr>';
										}
										resultats += '<tr typeEnregistrement="'+typeEnregistrement+'" class="pointer getJoueurSurvol'+selected+'" id="'+id+'" nomSeigneur="'+nomSeigneur+'" nomRoyaume="'+nomRoyaume+'"><td>';

										if(fieldToDisplay=='nomSeigneur_nomRoyaume')	{
											resultats += nomSeigneur+' ~ '+nomRoyaume;
										}
										else if(fieldToDisplay=='nomSeigneur')	{
											resultats += nomSeigneur;
										}

										premierJoueur = false;
									}

									resultats += '</td></tr>';

									++nbResultats;
								}
							);
							resultats += '</table>';

							if(nbResultats>0)	{
								$('#resultats').html(resultats);

								$('.getJoueurSurvol').hover(
									function()	{$('.getJoueurSurvol').removeClass('backFonce selected');$(this).addClass('backFonce selected');},
									function()	{	 }
								);

								// Action au click ou entree (cf trigger)
								$('.getJoueurSurvol').click(
									function()	{
										// Si c'est un joueur
										if($(this).attr('typeEnregistrement') == 'joueur') {
											id = $(this).attr('id');
											nomSeigneur = $(this).attr('nomSeigneur');
											nomRoyaume = $(this).attr('nomRoyaume');
											nomGuilde = '';
											$('.getJoueurResults').remove();
											// code spécial pour que le nom du joueur reste dans le champ
											if(contains(window.location.href, 'espionnage')) {
												get('nomEnnemi').value = (fieldToDisplay == 'nomSeigneur') ? nomSeigneur : nomSeigneur+" ~ "+nomRoyaume;
											}
											eval(functionToCall);
										}
										// si c'est une guilde
										else if($(this).attr('typeEnregistrement') == 'guilde') {
											nomGuilde = $(this).attr('nomGuilde');
											$('.getJoueurResults').remove();
											$(this).find('td').find('span').each(function () {
													id = $(this).attr('idJoueur');
													nomSeigneur = $(this).attr('nomSeigneur');
													nomRoyaume = $(this).attr('nomRoyaume');
													eval(functionToCall);
												}
											);
										}

										// TODO : Pas bon du tout le coup de l'espionnage...
										var doNotEmpty = $(THIS).attr('doNotEmpty')=='true' || contains(window.location.href, 'espionnage') ? true : false;
										if(!doNotEmpty) {
											$(THIS).val('');
										}

										return false;
									}
								);

							}
							else {
								$('#resultats').html('<span class="grisFonce italique">Aucun r&eacute;sultat...</span>');
							}

							$('.getJoueurSurvol').live('mousedown', function () {return false;});
						}
					);
				}
			}
			else if(alreadyDisplayed)	{
				$(this).next().remove();
			}
  	}
  ).live('blur', function () {$('.getJoueurResults').remove();})
  .live('focus', function () {$(this).val('');$('.getJoueurResults').remove();});

  if($('#pubdirecte').length != 0) {	// On cache si y'a plus de pub pubdirecte à afficher
	if($('#pubdirecte a').attr('href') == 'http://www.pubdirecte.com/?said=24035') {
        //$('#pubdirecte').html('');
	}
  }


  redirectionInactivite();
});

function checkPub() {
  $('document').ready(function() {
      if($('#pubdirecte').length == 0) {
        if(Math.round(Math.random()*10)==1) {
          $('h1').after('<div class="width500 marginAuto rouge tout_petit">Pour la survie du site, n\'oubliez pas d\'activer l\'affichage des publicit&eacute;s sur votre navigateur. Merci :)</div>');
        }
      }
  });
}

function numberFormat(nombre) {
	if (nombre==0) return nombre;
	else {
		var nbString = nombre.toString(), longueurNb = nbString.length;
		if (longueurNb <4) 	return nombre;
		else
		    return ((longueurNb % 3) ? nbString.substr(0, longueurNb % 3) + ' ' : '') + nbString.substr(longueurNb % 3).match(new RegExp('[0-9]{3}', 'g')).join(' ');
	}
}

function check(id)	{
	document.getElementById(id).checked = !document.getElementById(id).checked;

}
function checkRadio(id)	{
	document.getElementById(id).checked = true;
}
function display(id)	{
	document.getElementById(id).style.display=(document.getElementById(id).style.display=='block') ? 'none':'block';
}
function getXhr()	{
  var xhr = null;
	if(window.XMLHttpRequest)
		xhr = new XMLHttpRequest();
	else if(window.ActiveXObject){
		try {xhr = new ActiveXObject("Msxml2.XMLHTTP");}
		catch (e) {xhr = new ActiveXObject("Microsoft.XMLHTTP");}
	}
	else {
	   alert("Votre navigateur ne supporte pas la technologie AJAX utilisee sur LLDC, merci de le mettre a jour ou de telecharger Firefox");
	   xhr = false;
	}
    return xhr;
}
function Popup(lien,nom,config)	{
	window.open(lien, nom, config);
}
var radioPrecedent = 0;
function radio(id)	{
	if(!(document.getElementById(id).disabled))	{
		document.getElementById(id).checked = true;
		if(radioPrecedent==0)
			radioPrecedent = id;
	}
}

setInterval("session()", 600000);
function session()	{
	xhr = getXhr();
	xhr.open("POST", "../ajax/session_ajax.php", true);
	xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	xhr.send('');
}

function get(id)	{return document.getElementById(id);}

function ajax(pageDest, idDisplayDiv, data, call, autoRequest)	{
	autoRequest = autoRequest=='true';
	if(!autoRequest)
		document.body.style.cursor = 'wait';

	var xhr = getXhr();
	xhr.onreadystatechange = function(){
		if(xhr.readyState==4)	{
			if(idDisplayDiv)
				get(idDisplayDiv).innerHTML = xhr.responseText;
			if(call)
				eval(call);
			if(!autoRequest)	{
				document.body.style.cursor = 'default';
				stopToolTip();
				if(pageDest!='../ajax/refreshRessources_ajax.php' && get('entetecorps'))
					refreshRessources();
			}
			return xhr.responseText;
		}
	}

	xhr.open("POST", pageDest, true);
	xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	xhr.send(data);
}

function refreshRessources()	{
	ajax('../ajax/refreshRessources_ajax.php', 'entetecorps', 'none', '', 'true');
}


function contains(string, element)	{
	return string.indexOf(element, 0)!=-1;
}

var inactiviteTimeout;
function redirectionInactivite()	{
	if(!contains(window.location.href, "/royaume.php") && !contains(window.location.href, "/amneroth.php") && contains(window.location.href, "<?php echo URL_ESPACE_MEMBRE; ?>"))	{
		clearTimeout(inactiviteTimeout);
		inactiviteTimeout = setTimeout('redirection("'+redirectionInactivitePage+'")', delaiAvantRedirection);
	}
}
function redirection(page)	{
	window.location=page;
}
function goTo(id)	{
	get(id).focus();
	get(id).blur();
}
function keyPressedEnter(touche, fonction) {
	if(touche==13) {eval(fonction);}
}

var lastKey=0;
function keyPressedCtrlEntree(touche, fonction, confirmText)	{
	if((lastKey==17 && touche==13) || (lastKey==13 && touche==17))	{
		if(confirm(confirmText))
			eval(fonction);
	}
	else	{
		lastKey=touche;
	}
	setTimeout('clearKey();', 5000);
}
function clearKey()	{
	lastKey=0;
}

//	ToolTip & PopUp
var x, y, conteneur, toolTipDisplay = false, popUpDisplay = false, popUpX, popUpY, popUpXtmp, popUpYtmp;

document.write('<div class="toolTip noir tres_petit back_parchemin" id="toolTip">Erreur</div>');
document.write('<div class="popUp noir tres_petit back_parchemin" id="popUp">Rechargez...</div>');

if(document.getElementById)	{
	var toolTip = get('toolTip').style;
	var popUp = get('popUp').style;

	if(navigator.appName.substring(0,3)=='Net')
		document.captureEvents(Event.MOUSEMOVE);
	document.onmousemove = getMouse;
}

function getMouse(e)	{
	if(toolTipDisplay)	{
		x = (navigator.appName.substring(0,3)=='Net' || navigator.appName=='Opera') ? e.pageX : event.x+document.body.scrollLeft;
		y = (navigator.appName.substring(0,3)=='Net' || navigator.appName=='Opera') ? e.pageY : event.y+document.body.scrollTop;
		toolTip.left = (x-50)+'px';
		toolTip.top = (y+20)+'px';
	}
	popUpXtmp = (navigator.appName.substring(0,3)=='Net' || navigator.appName=='Opera') ? e.pageX : event.x+document.body.scrollLeft;
	popUpYtmp = (navigator.appName.substring(0,3)=='Net' || navigator.appName=='Opera') ? e.pageY : event.y+document.body.scrollTop;
}

function stopToolTip()	{
	toolTip.visibility = 'hidden';
	toolTipDisplay = false;
}
function startToolTip(texte)	{
	get('toolTip').innerHTML = texte;
 toolTip.visibility = 'visible';
	toolTipDisplay = true;
}

function openPopUp(texte, shouldReturnFalse, center, intTop)	{
	if(!popUpDisplay)	{
		popUpX = popUpXtmp;
		popUpY = popUpYtmp;
	 popUp.visibility = 'visible';
		get('popUp').innerHTML = texte;
		if(!center)	{
			popUp.left = (popUpX-85)+'px';
			popUp.top = (popUpY-10)+'px';
			popUp.width = '';
		}
		else	{
			if(!intTop)
				intTop = 300;
			popUp.top = (popUpY-intTop)+'px';
			popUp.width = '40%';
			popUp.left = '30%';
		}
		popUpDisplay = true;
	}
	else
		closePopUp(shouldReturnFalse);

	if(shouldReturnFalse)
		return false;
}
function closePopUp(shouldReturnFalse)	{
	popUp.visibility = 'hidden';
	popUpDisplay = false;
}

/* Recherche de joueurs */
function rechercheJoueur(idChamp, valeur, fonction) {
	if(valeur.length >= 3) {
		tableau = idChamp.split(/_/);
		ajax('../ajax/rechercheJoueur_ajax.php', 'resultats_'+tableau[1], 'idChamp='+tableau[1]+'&chaine='+escape(valeur)+'&fonction='+escape(fonction.replace(/\+/g,'[plus]')), '', 'true');
		get('resultats_'+tableau[1]).style.display = '';
	}
}
function selectionJoueur(idChamp, idduj, joueur, fonction) {
	if(fonction != '') {
		eval(fonction);
	}
	else {
		get('selection_'+idChamp).value = idduj;
		get('recherche_'+idChamp).value = joueur;
	}
	get('resultats_'+tableau[1]).style.display = 'none';
}

function topPage()	{
	get('topPage').focus();
}

// Tous les champs avec une classe formatChamp sont formatés automatiquement
$('input.formatChamp').live("keyup", function() {
	if($(this).caret().start == $(this).caret().end) {
		anciennePosition = $(this).caret().start;
		ancienneValeur = $(this).val();
		nouvelleValeur = numberFormat($(this).val().replace(' ', '').replace(' ', '').replace(' ', ''));
		ancienneLongueur = ancienneValeur.length;
		nouvelleLongueur = nouvelleValeur.length;

		if(ancienneLongueur > nouvelleLongueur && ancienneLongueur-nouvelleLongueur == 1) {
			nouvellePosition = anciennePosition-1;
		}
		else if(ancienneLongueur < nouvelleLongueur && nouvelleLongueur-ancienneLongueur == 1) {
			nouvellePosition = anciennePosition+1;
		}
		else {
			nouvellePosition = anciennePosition;
		}

		$(this).val(nouvelleValeur);
		$(this).setCursorPosition(nouvellePosition);
	}
});

$('input.formatChamp').live("focus blur", function() {
	if($(this).val() == "0" || $(this).val() < 0) {
		$(this).val('');
	}
});

new function($) {
  $.fn.setCursorPosition = function(pos) {
    if ($(this).get(0).setSelectionRange) {
      $(this).get(0).setSelectionRange(pos, pos);
    } else if ($(this).get(0).createTextRange) {
      var range = $(this).get(0).createTextRange();
      range.collapse(true);
      range.moveEnd('character', pos);
      range.moveStart('character', pos);
      range.select();
    }
  }
}(jQuery);

